C# C:分为子字符串的字符串,不包括制表符
我有一个类似以下内容的文件: 0 4 5 6.9尝试将IndexOf与制表符一起使用,而不是与空格一起使用:C# C:分为子字符串的字符串,不包括制表符,c#,arrays,string,substring,C#,Arrays,String,Substring,我有一个类似以下内容的文件: 0 4 5 6.9尝试将IndexOf与制表符一起使用,而不是与空格一起使用: int xlength= line.IndexOf("\t"); //"\t" - to find tabs 另外,在每个IndexOf调用中使用\t。使用Split、Linq和LinqPad如何 void Main() { var lines = new List<string> { "0\t4 5", "6\t9\t9" }; lines
int xlength= line.IndexOf("\t"); //"\t" - to find tabs
另外,在每个IndexOf调用中使用\t。使用Split、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();
}
尝试改用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!
}
要为上述建议添加一点额外的容量,可以使用Regex.Matches,如下所示:
string line = "1\t-25\t5";
var numbers = Regex.Matches(line, @"-?\d+");
foreach (var number in numbers)
Console.WriteLine(number);
然后将这些数字解析为整数
这有两个好处
它可以处理负数,并且
即使没有使用标签或标签不可靠,它也会成功地取出数字。
选项卡由\t表示。我建议使用拆分方法。考虑不要重新创建String。S拆除法或.NET TeXFieldPARSER类。有数百个关于读取CSV文件的问题。请澄清为什么现有答案不适用于您。
string line = "1\t-25\t5";
var numbers = Regex.Matches(line, @"-?\d+");
foreach (var number in numbers)
Console.WriteLine(number);