-6

我的文本文件看起来像这样

我的文本.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
..... 
4

1 回答 1

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);
}
于 2013-03-24T16:56:08.667 回答