拆分带有修剪空白的字符串C#

时间:2014-03-07 02:55:40

标签: c# string split removing-whitespace

我希望能够将带有','的字符串拆分为分隔符,并且仅在生成的分割的两侧修剪空格。例如:

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

3 个答案:

答案 0 :(得分:7)

您可以在LINQ之后使用Split

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

或者您可以将您的分隔符更改为", "(逗号+空格)。这也适用于此案例,因为每个white-space后只有一个comma

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

答案 1 :(得分:0)

对于Non-Linq解决方案,您只需在解决方案中添加一行xtra代码

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

答案 2 :(得分:0)

另一种方式:

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