2017-03-24 156 views
0

我想用文本文件中的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 「無」 到 「數字」 取代:

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. 
+1

另一種方法你總是想只更換線3-5? –

+0

用例如'ReadAllLines'讀取文件,找到你想要的行,執行替換並再次寫出它們。 –

+0

正如@MightyBadaboom所說,我們需要更好地理解這個問題,就如何判斷一條線是否應該改變而言。然後,你應該顯示你已經嘗試過的代碼,以及它沒有做到你想要的。然後我們將能夠給你適當的,有用的,指導性的幫助。 – ClickRick

回答

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

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); 
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); 
相關問題