How can I split and crop a string into pieces on the same line?

I want to break this line:

string line = "First Name ; string ; firstName"; 

into the array of their cropped versions:

 "First Name" "string" "firstName" 

How can I do this all on one line? The following is the error "cannot convert void type":

 List<string> parts = line.Split(';').ToList().ForEach(p => p.Trim()); 
+79
split c # trim
Nov 13 '09 at 10:06
source share
7 answers

Try

 List<string> parts = line.Split(';').Select(p => p.Trim()).ToList(); 

FYI, the Foreach method takes an action (takes T and returns void) for the parameter, and your lambda returns the string as string.Trim returns the string

The Foreach extension method is designed to change the state of objects in a collection. Since the string is immutable, this will have no effect

Hope this helps; o)

Cedric

+192
Nov 13 '09 at 10:10
source share

The ForEach method does not return anything, so you cannot assign it to a variable.

Use the Select extension method instead:

 List<string> parts = line.Split(';').Select(p => p.Trim()).ToList(); 
+17
Nov 13 '09 at 10:11
source share

Since p.Trim () returns a new line.

You need to use:

 List<string> parts = line.Split(';').Select(p => p.Trim()).ToList(); 
+3
Nov 13 '09 at 10:11
source share

Alternatively try the following:

 string[] parts = Regex.Split(line, "\\s*;\\s*"); 
+3
Jul 24 '13 at 9:08
source share

try using regex:

 List<string> parts = System.Text.RegularExpressions.Regex.Split(line, @"\s*;\s*").ToList(); 
+2
Jul 07 '15 at 10:58
source share

Here's the 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(); } 
+1
May 29 '15 at 15:34
source share

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:

bean

John

person

Francis

Luke

lee

bean

Explain pattern [,; \ s]: match one or one of ;;; or whitespace

0
Dec 21 '16 at 1:50
source share



All Articles