C# 将字符串拆分为数组,删除空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13645960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split string to array, remove empty spaces
提问by Le Viet Hung
I have a question about splitting string. I want to split string, but when in string see chars "" then don't split and remove empty spaces.
我有一个关于拆分字符串的问题。我想拆分字符串,但是当在字符串中看到字符 "" 时,不要拆分并删除空格。
My String:
我的字符串:
String tmp = "abc 123 \"Edk k3\" String;";
Result:
结果:
1: abc
2: 123
3: Edkk3 // don't split after "" and remove empty spaces
4: String
My code for result, but I don't know how to remove empty spaces in ""
我的结果代码,但我不知道如何删除“”中的空格
var tmpList = tmp.Split(new[] { '"' }).SelectMany((s, i) =>
{
if (i % 2 == 1) return new[] { s };
return s.Split(new[] { ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
}).ToList();
Or but this doesn't see "", so it splits everything
或者但这没有看到“”,所以它分裂了一切
string[] tmpList = tmp.Split(new Char[] { ' ', ';', '\"', ',' }, StringSplitOptions.RemoveEmptyEntries);
采纳答案by SergeyS
Add .Replace(" ","")
添加 .Replace(" ","")
String tmp = @"abc 123 ""Edk k3"" String;";
var tmpList = tmp.Split(new[] { '"' }).SelectMany((s, i) =>
{
if (i % 2 == 1) return new[] { s.Replace(" ", "") };
return s.Split(new[] { ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
}).ToList();
回答by Oded
string.Splitis not suitable for what you want to do, as you can't tell it to ignore what is in the ".
string.Split不适合您想做的事情,因为您不能告诉它忽略".
I wouldn't go with Regexeither, as this can get complicated and memory intensive (for long strings).
我也不会选择Regex,因为这会变得复杂且内存密集(对于长字符串)。
Implement your own parser - using a state machine to track whether you are within a quoted portion.
实现您自己的解析器 - 使用状态机来跟踪您是否在引用部分内。
回答by Guffa
You can use a regular expression. Instead of splitting, specify what you want to keep.
您可以使用正则表达式。不要拆分,而是指定要保留的内容。
Example:
例子:
string tmp = "abc 123 \"Edk k3\" String;";
MatchCollection m = Regex.Matches(tmp, @"""(.*?)""|([^ ]+)");
foreach (Match s in m) {
Console.WriteLine(s.Groups[1].Value.Replace(" ", "") + s.Groups[2].Value);
}
Output:
输出:
abc
123
Edkk3
String;

