Reputation: 85
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
Reputation: 854
Another way:
string str = "The, quick brown, fox";
string[] result = Regex.Split(str, @"\s*,\s*");
Upvotes: 1
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
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