user3390855
user3390855

Reputation: 85

split string with trimmed whitespace C#

I want to be able to split a string with ',' as a delimiter, and only trim whitespace on the sides of the resulting split. For example:

string str = "The, quick brown, fox";
string[] splitsWithTrim = str.split(',', also trim whitespace somehow?);
foreach (string s in splitsWithTrim)
    Console.WriteLine(s);

//output wanted:
//The
//quick brown
//fox

Upvotes: 2

Views: 2631

Answers (3)

Dmitriy Finozhenok
Dmitriy Finozhenok

Reputation: 854

Another way:

string str = "The, quick brown, fox"; 
string[] result = Regex.Split(str, @"\s*,\s*");

Upvotes: 1

Selman Genç
Selman Genç

Reputation: 101731

You can use LINQ after Split:

string str = "The, quick brown, fox";
string[] splitsWithTrim = str.Split(',').Select(x => x.Trim()).ToArray();

Or you can change your seperator to ", " (comma + space).It is also work for this case because there is only one white-space after each comma:

string[] splitsWithTrim = str.Split(new[] { ", " }, StringSplitOptions.None);

Upvotes: 9

Parimal Raj
Parimal Raj

Reputation: 20595

For a Non-Linq solution, you just need to add one xtra line of code in solution

string str = "The, quick brown, fox";
string[] splitsWithTrim = str.split(',', also trim whitespace somehow?);
foreach (string s in splitsWithTrim)
{
    Console.WriteLine(s.Trim());
}

Upvotes: 0

Related Questions