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

C#.NetSplitTrim

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

After .net 5, the solution is as simple as:

List<string> parts = line.Split(';', StringSplitOptions.TrimEntries);

Solution 4 - C#

Because p.Trim() returns a new string.

You need to use:

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

Solution 5 - C#

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

Solution 6 - C#

Alternatively try this:

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

Solution 7 - C#

try using Regex :

List<string> parts = System.Text.RegularExpressions.Regex.Split(line, @"\s*;\s*").ToList();

Solution 8 - C#

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;
}

Solution 9 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEdward TanguayView Question on Stackoverflow
Solution 1 - C#Cédric RupView Answer on Stackoverflow
Solution 2 - C#GuffaView Answer on Stackoverflow
Solution 3 - C#Guilherme FerreiraView Answer on Stackoverflow
Solution 4 - C#Matt BreckonView Answer on Stackoverflow
Solution 5 - C#LawManView Answer on Stackoverflow
Solution 6 - C#Lawrence PhillipsView Answer on Stackoverflow
Solution 7 - C#user2826608View Answer on Stackoverflow
Solution 8 - C#foxjazzHackView Answer on Stackoverflow
Solution 9 - C#Hung VuView Answer on Stackoverflow