[英]C# .NET - How can I split string with a tab separator?
I have this string in my code: 我的代码中包含以下字符串:
string test = @"aaaaa aaaaa aaaaa bbbb ttttt tttttt
33333 44444 777777 77777 88888 8888 8888 88888 88888
wwwww wwwww wwwwww wwwww wwwww wwwwww";
And here is my code spliting string by new line character and tab. 这是我的代码,通过换行符和制表符拆分字符串。
foreach (var line in test.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
foreach (var lineItem in line.Split('\t'))
{
}
}
In first interation of first loop line variable is "aaaaa aaaaa aaaaa bbbb ttttt tttttt" and this is correct, but in seconds loop first interation variable lineItem is the same, it doesn't split this string with tab separator. 在第一个循环的第一个交互行变量是“ aaaaa aaaaa aaaaa bbbb ttttt tttttt” ,这是正确的,但是在几秒钟的循环中,第一个交互变量lineItem是相同的,因此不会使用制表符分隔符拆分此字符串。 Why it's happening?
为什么会这样呢?
Are you sure your string has tab characters ? 您确定您的字符串中包含制表符吗? try using
Split()
it will split by tab and white-space: 尝试使用
Split()
它将按制表符和空格分开:
foreach (var lineItem in line.Split())
{
}
The reason it does not work is because the tabs
are not tabs in your string test
- see this: 它不起作用的原因是
tabs
不是您的string test
选项卡-请参见:
The first line is what i generated myself from MS Excel.
第一行是我从MS Excel中生成的。 Use regex to correctly represent any whitespace char (even for Unicode escape sequences)
使用正则表达式正确表示任何空格字符(即使对于Unicode转义序列)
Regex regex = new Regex(@"\s");
string[] bits = regex.Split(line);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.