我希望能够将带有','的字符串拆分为分隔符,并且仅在生成的分割的两侧修剪空格。例如:
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
答案 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*");