【问题标题】:read number from a text file and replace with a something else [closed]从文本文件中读取数字并替换为其他内容[关闭]
【发布时间】:2013-03-14 03:06:05
【问题描述】:

我的文本文件是这样的

mytext.txt

1. This is line one
2. This is line two
3. This is line three
.....

现在我想使用 c# 读取 mytext.txt,然后像这样替换这些行并将其保存到文本文件中。

Number. This is line one
Number. This is line two
Number. This is line three
..... 

【问题讨论】:

  • 所以您希望我们为您编写所有代码?这不会发生,展示你的努力。
  • 我认为它确实发生了:)

标签: c# io


【解决方案1】:

我会给你代码,但解释一下每个步骤的作用,以便你可以从中学习:

// assume that System.IO is included (in a using statement)
// reads the file, changes all leading integers to "Number", and writes the changes
void rewriteNumbers(string file)
{
    // get the lines from the file
    string[] lines = File.ReadAllLines(file);
    // for each line, do:
    for (int i = 0; i < lines.Length; i++)
    {
        // trim all number characters from the beginning of the line, and
        // write "Number" to the beginning
        lines[i] = "Number" + lines[i].TrimStart('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    }
    // write the changes back to the file
    File.WriteAllLines(file, lines);
}

【讨论】:

  • antonijn 的解决方案是另一种看待问题的方式:找到第一个句点,然后删除它之前的所有字符。这也行...
  • 所以你不是反对者?
  • 我没有125声望;我不能成为downvoter...
  • 是的,这是一个很好的观点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
相关资源
最近更新 更多