سؤال

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
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

Another way:

string str = "The, quick brown, fox"; 
string[] result = Regex.Split(str, @"\s*,\s*");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top