2017-02-25 71 views
0

我有一个看起来是这样的文件:C#:字符串分为子,但不包括标签

0 4 5 
 
6 9 9

等,每排三个数字,由制表符分隔。我从文件中的行的数组:

string[] lines = File.ReadAllLines(theFile);

对于每一行,我打电话,其预期的结果是返回一个整数数组的函数。下面是我的代码看起来像截至目前:

public int[] getPoint(string line) 
 
    { 
 
     int xlength= line.IndexOf(" "); //find location of first white space 
 
     int x= Int32.Parse(line.Substring(0, xlength)); //find x-coordinate and turn it from a string to an int 
 

 
     int ylength = line.IndexOf(" ", xlength); //find next white space 
 
     int y = Int32.Parse(line.Substring(xlength + 1, ylength)); //y-coordinate starts after first white space and ends before next 
 

 
     int z = Int32.Parse(line.Substring(ylength + 1, line.Length)); //z starts after 2nd white space and goes through end of line 
 
     
 
     return new int[] { x, y, z }; //return a new point! 
 
    }

我的问题是用的IndexOf(字符串)功能。它不识别标签。我怎么写这个,以便我的每个getPoint函数达到它的目的?谢谢。

+3

选项卡由“\ t”表示。我建议使用Split()方法。 –

+0

考虑不要重新创建String.Split()方法或.NET TextFieldParser类。 –

+0

关于阅读CSV文件有几百个问题。请澄清为什么现有的答案不适合你。 –

回答

1

尝试使用IndexOf()与标签,不能以空格:

int xlength= line.IndexOf("\t"); //"\t" - to find tabs 

而且,在每一个IndexOf()调用中使用"\t"

0

这样如何使用斯普利特和LINQ和LinqPad

void Main() 
{ 
    var lines = new List<string> { "0\t4 5", "6\t9\t9" }; 

    lines.Select(l => GetPoint(l)).Dump(); 
} 

static int[] GetPoint(string s) 
{ 
    var values = s.Split(new[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries); 

    return values.Select(v => int.Parse(v)).ToArray(); 
} 

当然,你可以使用

File.ReadLines("path").Select(l => GetPoint(l)).Dump(); 
0

尝试使用ReadLines方法来代替。 RealLines将按要求将文件逐行读入内存。另外,请尝试使用Split方法。如果找到的字符串不能解析为int,我还会添加错误处理。下面是一些代码来指导你,但你可能需要调整它来满足您的需求:

foreach (var thisLine in File.ReadLines(theFile)) 
{ 
    int[] point = getPoint(thisLine); 
} 

public int[] getPoint(string line) 
{ 
    // Split by tab or space 
    string[] portions = line.Split(new char[] { ' ', '\t' }); 

    int x = Int32.Parse(portions[0]); //find x-coordinate and turn it from a string to an int 

    int y = Int32.Parse(portions[1]); //y-coordinate starts after first white space and ends before next 

    int z = Int32.Parse(portions[2]); //z starts after 2nd white space and goes through end of line 

    return new int[] { x, y, z }; //return a new point! 
} 
0

要多一点额外的容量添加到上述建议,你可以使用Regex.Matches()如下:

 string line = "1\t-25\t5"; 

     var numbers = Regex.Matches(line, @"-?\d+"); 
     foreach (var number in numbers) 
      Console.WriteLine(number); 

然后将这些数字解析为整数。

这有两个好处。

  1. 它可以处理负数,并
  2. 这将成功地拉出数,即使不使用或不可靠的标签。
相关问题