简体   繁体   English

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

[英]string.Split function in c# tab delimiter

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());

        .......
 }

I guess you are using something like 我想你正在使用类似的东西

string sep = @"\t";

in this case sep will hold \\\\t double back slash 在这种情况下,sep将保持\\\\t双反斜杠

use string sep = "\\t" 使用string sep = "\\t"

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

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

pass parameter value as Decimal number of \\t (tab) and convert to it Char. 将参数值作为\\ t(标签)的十进制数传递并转换为它。

 int delimeter =9;

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

 char _delimeter = Convert.ToChar(delimeter);

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

Happy Programming. 快乐的编程。

If you pass in "\\t" as the delimiter nothing will change it to "\\t". 如果传入“\\ t”作为分隔符,则不会将其更改为“\\ t”。 Something else is double escaping your tab. 其他东西是双重逃避你的标签。

    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);
    }

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. 这段代码适合我。

你试过吗:Environment.NewLine?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM