I want to split this line:
string line = \"First Name ; string ; firstName\";
into an array of their trimmed versions:
\"Fi
Try
List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
FYI, the Foreach method takes an Action (takes T and returns void) for parameter, and your lambda return a string as string.Trim return a string
Foreach extension method is meant to modify the state of objects within the collection. As string are immutable, this would have no effect
Hope it helps ;o)
Cédric
try using Regex :
List<string> parts = System.Text.RegularExpressions.Regex.Split(line, @"\s*;\s*").ToList();
Here's an extension method...
public static string[] SplitAndTrim(this string text, char separator)
{
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
return text.Split(separator).Select(t => t.Trim()).ToArray();
}
Split returns string[] type. Write an extension method:
public static string[] SplitTrim(this string data, char arg)
{
string[] ar = data.Split(arg);
for (int i = 0; i < ar.Length; i++)
{
ar[i] = ar[i].Trim();
}
return ar;
}
I liked your solution so I decided to add to it and make it more usable.
public static string[] SplitAndTrim(this string data, char[] arg)
{
return SplitAndTrim(data, arg, StringSplitOptions.None);
}
public static string[] SplitAndTrim(this string data, char[] arg,
StringSplitOptions sso)
{
string[] ar = data.Split(arg, sso);
for (int i = 0; i < ar.Length; i++)
ar[i] = ar[i].Trim();
return ar;
}
Use Regex
string a="bob, jon,man; francis;luke; lee bob";
String pattern = @"[,;\s]";
String[] elements = Regex.Split(a, pattern).Where(item=>!String.IsNullOrEmpty(item)).Select(item=>item.Trim()).ToArray();;
foreach (string item in elements){
Console.WriteLine(item.Trim());
Result:
bob
jon
man
francis
luke
lee
bob
Explain pattern [,;\s]: Match one occurrence of either the , ; or space character
Alternatively try this:
string[] parts = Regex.Split(line, "\\s*;\\s*");