Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split and trim a string into parts all on one line?

Tags:

c#

.net

split

trim

People also ask

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.


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


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();

Because p.Trim() returns a new string.

You need to use:

List<string> parts = line.Split(';').Select(p => p.Trim()).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();
    }

Alternatively try this:

string[] parts = Regex.Split(line, "\\s*;\\s*");