从文本文件中读取数字,并将其替换为其他内容
本文关键字:替换 其他 文件 文本 读取 数字 | 更新日期: 2023-09-27 18:05:38
我的文本文件是这样的
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
.....
我将给出代码,但解释每一步的作用,以便您可以从中学习:
// 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);
}