c#制表符分隔符中的string.Split函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12384905/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:04:36  来源:igfitidea点击:

string.Split function in c# tab delimiter

c#stringsplit

提问by Dimitar Tsonev

I have a function which reads a delimited file.

我有一个读取分隔文件的函数。

The delimiter is passed to the function by string argument. The problem is, when I pass the "\t"delimiter, it ends up like "\\t"and therefore, Split is unable to find this sequence.

分隔符通过字符串参数传递给函数。问题是,当我通过"\t"分隔符时,它最终像这样"\\t",因此 Split 无法找到这个序列。

How can I resolve this issue?

我该如何解决这个问题?

private void ReadFromFile(string filename, string delimiter)
{

        StreamReader sr = new StreamReader(filename, Encoding.Default);
        string[] firstLine = sr.ReadLine().Split(t.ToCharArray());

        .......
 }

采纳答案by Vignesh.N

I guess you are using something like

我猜你正在使用类似的东西

string sep = @"\t";

in this case sep will hold \\tdouble back slash

在这种情况下 sep 将保留\\t双反斜杠

use string sep = "\t"

string sep = "\t"

string content = "Hello\tWorld";
string sep = "\t";
string[] splitContent = content.Split(sep.ToCharArray());

回答by MichaelT

use single qutes for this like Split('\t'), this way you will be passing a char and not a string.

像 Split('\t') 这样使用单个 qutes,这样你将传递一个字符而不是一个字符串。

回答by Guy Lubovitch

did you try : Environment.NewLine ?

你试过: Environment.NewLine 吗?

回答by Slugart

If you pass in "\t" as the delimiter nothing will change it to "\t". Something else is double escaping your tab.

如果您传入“\t”作为分隔符,则不会将其更改为“\t”。其他东西是双重逃避您的标签。

    Blah("\t");
    private static void Blah(string s)
    {
        var chars = s.ToCharArray();
        Debug.Assert(chars.Length == 1);

        var parts = "blah\tblah\thello".Split(chars);            
        Debug.Assert(parts.Length == 3);
    }

回答by SandroG

Another way to do your split is replacing the TAB(\t) by a blank space on this way:

进行拆分的另一种方法是以这种方式用空格替换 TAB(\t) :

            if(linea.ToLower().Contains(@"\t"))
                linea = linea.Replace(@"\t", " ");
            retVal = linea.Trim().Split(' ')[1];

This code works for me.

这段代码对我有用。

回答by Buddhika De Silva

pass parameter value as Decimal number of \t (tab) and convert to it Char.

将参数值作为 \t (tab) 的十进制数传递并转换为 Char。

 int delimeter =9;

 // 9  ==> \t 
 // 10 ==> \n
 // 13 ==> \r

 char _delimeter = Convert.ToChar(delimeter);

 string[] rowData = fileContent.Split(_delimeter);

Happy Programming.

快乐编程。