我的文字文件如下所示
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
.....
答案 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);
}