从文本文件中读取数字并替换为其他内容

时间:2013-03-24 16:46:12

标签: c# io

我的文字文件如下所示

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
..... 

1 个答案:

答案 0 :(得分: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);
}