读取字符串中的每个数字c#

本文关键字:数字 字符串 读取 | 更新日期: 2024-09-19 17:35:37

假设这是我的txt文件:

line1
line2
line3
line4
line5

im用读取此文件的内容

 string line;
List<string> stdList = new List<string>();
StreamReader file = new StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{                
    stdList.Add(line);           
}
finally
{//need help here
}

现在我想读取stdList中的数据,但每2行只读取一个值(在这种情况下,我必须读取"line2"answers"line4")。有人能给我正路吗?

读取字符串中的每个数字c#

甚至比Yuck的方法更短它不需要一次性将整个文件读入内存:)

var list = File.ReadLines(filename)
               .Where((ignored, index) => index % 2 == 1)
               .ToList();

诚然,它确实需要.NET 4。关键部分是Where的重载,它提供了索引以及谓词要执行的值。我们并不真正关心值(这就是我将参数命名为ignored的原因),我们只想要奇数索引。显然,当我们构建列表时,我们关心值,但这很好——它只对谓词被忽略。

您可以将文件读取逻辑简化为一行,并通过以下方式循环通过其他行:

var lines = File.ReadAllLines(myFile);
for (var i = 1; i < lines.Length; i += 2) {
  // do something
}

EDIT:从i = 1开始,在您的示例中是line2

在循环中添加一个条件块和一个跟踪机制。(环路主体如下:)

int linesProcessed = 0;
if( linesProcessed % 2 == 1 ){
  // Read the line.
  stdList.Add(line);
}
else{
  // Don't read the line (Do nothing.)
}
linesProcessed++;

linesProcessed % 2 == 1表示:取我们已经处理的行数,并找到该数的mod 2。(整数除以2时的余数。)这将检查处理的行数是偶数还是奇数。

如果您没有处理任何行,它将被跳过(例如第1行,您的第一行。)如果您已经处理了一行或任何奇数行,请继续处理当前行(例如第2行)

如果模块化数学给你带来任何麻烦,请参阅以下问题:https://stackoverflow.com/a/90247/758446

试试这个:

string line;
List<string> stdList = new List<string>();
StreamReader file = new StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
    stdList.Add(line);
    var trash = file.ReadLine();  //this advances to the next line, and doesn't do anything with the result
}
finally
{
}