Delim Tabs in a string

时间:2017-03-28 13:27:07

标签: c# split

string s = "    1    16    34";
string[] words = s.Split('\t');
foreach (string word in words)
{
   Console.WriteLine(word);
}

我有一个如上所示的字符串格式,但是当我尝试使用转义标签时,它只是以原始格式输出完全相同的字符串,为什么不删除标签?

4 个答案:

答案 0 :(得分:2)

    string[] words = s.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string word in words)
                {
                    Console.WriteLine(word);
                }

我想我修好了。

它给了我这个输出。

1

16

34

我通过输出数组中的所有3来检查,以确保它们是分开的。

答案 1 :(得分:1)

Split上的

char[0] - 这将在所有空格上分开。 StringSplitOptions.RemoveEmptyEntries - 将删除空条目。

var words = myStr.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);

答案 2 :(得分:0)

尝试使用不带参数的split

string s = "    1   16  34";
string[] words = s.Split();
foreach (string word in words)
{
   Console.WriteLine();
}

这将按字符串的每个空格分割字符串。

答案 3 :(得分:0)

偏执解决方案:拆分在任何空白区域(空格,标签,不间断空间等)

  string s = "    1    16    34";

  string[] words = Regex
    .Matches(s, @"\S+")
    .OfType<Match>()
    .Select(m => m.Value)
    .ToArray();

正则表达式很可能过冲,但在脏数据的情况下可以提供帮助。