问题
I want to split this line:
string line = "First Name ; string ; firstName";
into an array of their trimmed versions:
"First Name"
"string"
"firstName"
How can I do this all on one line? The following gives me an error "cannot convert type void":
List<string> parts = line.Split(';').ToList().ForEach(p => p.Trim());
回答1:
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
回答2:
The ForEach
method doesn't return anything, so you can't assign that to a variable.
Use the Select
extension method instead:
List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
回答3:
Because p.Trim() returns a new string.
You need to use:
List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
回答4:
Alternatively try this:
string[] parts = Regex.Split(line, "\\s*;\\s*");
回答5:
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();
}
回答6:
try using Regex :
List<string> parts = System.Text.RegularExpressions.Regex.Split(line, @"\s*;\s*").ToList();
回答7:
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;
}
回答8:
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
来源:https://stackoverflow.com/questions/1728303/how-can-i-split-and-trim-a-string-into-parts-all-on-one-line