本文介绍了获取包含字符串的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取文本文件中包含指定字符串的行号?
How to get a line number that contains a specified string in a text file?
示例文本文件包含:
如何获取黄色"行号?我可以在指定的行中写一个字符串,可以说我想在第二行中写一个字符串吗?
How to get "Yellow" line number? and can i write a string in a specified line, lets say i want to write a string in line 2?
推荐答案
要在文本文件中查找一行,您需要从文件开头读取各行,直到找到为止:
To find a line in a text file, you need to read the lines from the start of the file until you find it:
string fileName = "file.txt";
string someString = "Yellow";
string[] lines = File.ReadAllLines(fileName);
int found = -1;
for (int i = 0; i < lines.Length; i++) {
if (lines[i].Contains(someString)) {
found = i;
break;
}
}
如果要更改文件中的一行,则必须读取整个文件,然后将更改后的行写回去:
If you want to change a line in a file, you have to read the entire file and write it back with the changed line:
string[] lines = File.ReadAllLines(fileName);
lines[1] = "Black";
File.WriteAllLines(fileName, lines);
这篇关于获取包含字符串的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!