替换文本文件中特定行中的字符串

时间:2017-03-24 08:33:49

标签: c# string

我想在Text文件中用String2替换String1。

文字档案

This is line no 1. 
This is line no 2. 
This is line no 3.
This is line no 4. 
This is line no 5. 
This is line no 6.

字符串

String1 : no
string2 : number

我希望这种类型的输出行3到5替换为“no”到“number”:

This is line no 1. 
This is line no 2. 
This is line number 3.
This is line number 4. 
This is line number 5. 
This is line no 6.

3 个答案:

答案 0 :(得分:5)

使用Linq

的另一种方法
string[] file = File.ReadAllLines(@"c:\yourfile.txt");
file = file.Select((x, i) => i > 1 && i < 5 ? x.Replace("no", "number") : x).ToArray();
File.WriteAllLines(@"c:\yourfile.txt", file);

答案 1 :(得分:1)

System.IO.File.ReadAllLines(string path)可能对您有帮助。

它从文本文件创建字符串数组,您编辑数组,并使用System.IO.File.WriteAllLines保存它。

string[] Strings = File.ReadAllLines(/*File Path Here*/);
Strings[2] = Strings[2].Replace("no", "number");
Strings[3] = Strings[3].Replace("no", "number");
Strings[4] = Strings[4].Replace("no", "number");
File.WriteAllLines(/*File Path Here*/, Strings);

答案 2 :(得分:1)

你应该试试这个:

// Read all lines from text file.
String[] lines = File.ReadAllLines("path to file");
for(int i = 3; i <= 5; i++) // From line 3 to line 5
{
    // Replace 'no' to 'number' in 3 - 5 lines
    lines[i - 1] = lines[i - 1].Replace("no", "number");
}

// Rewrite lines to file
File.WriteAllLines("path to file", lines);