2011-07-19 58 views
2

我需要替換文件的每一行中的某些字符。該文件沒有分隔,但每行都有固定的格式。例如,我需要將5個問號替換爲'x'。 5個questionmarks需要在每行被替換在位置10被發現因此,例如:幫助解析文件的行並替換子字符串

輸入文件:

abdfg trr?????456 
g?????dhs?????diu 
eerrttyycdhjjhddd 

輸出文件應該是:

abdfg trrxxxxx456 
g?????dhsxxxxxdiu 
eerrttyycdhjjhddd 

輸出文件將被保存爲一個不同的文件到一個特定的位置

什麼是最好的方式來做到這一點在VB.NET(我有點新的VB,所以任何代碼示例會有所幫助)?

+0

是否總是爲每個文件相同,或者它的文件之間有什麼不同?還有,問號總是一樣的嗎? – Nightfirecat

+0

是的,它始終是相同數量的問題標記,並且始終顯示在同一個索引上(每行相同)。每個文件都是不同的,但格式是相同的......將每行的位置10中的5個問號替換爲xxxxx。 – Prabhu

回答

5

一種可能的解決方案是使用StreamReader(通過ReadLine()方法)解析文件中的每一行。當您在每行中閱讀時,您可以使用StreamWriter將原始行寫出(通過WriteLine(String)方法),並進行一次調整。如果生產線符合您的替換要求,您將使用String.Replace(String, String)方法替換替換字符串的舊字符串。

這裏是一個解決方案(上面的樣本數據編譯和測試)。你仍然需要添加一些異常處理(至少是,確保該文件存在在前):

Public Shared Sub ReplacementExample(string originalFile, string newFile) 

    ' Read contents of "oringalFile" 
    ' Replace 5 ? characters with 5 x characters. 
    ' Write output to the "newFile" 
    ' Note: Only do so if the ? characters begin at position 10 


    Const replaceMe As String = "?????" 
    Const replacement As String = "xxxxx" 

    Dim line As String = Nothing 

    Using r As New StreamReader(originalFile) 
     Using w As New StreamWriter(newFile) 

      line = r.ReadLine() 

      While Not line Is Nothing 
       w.WriteLine(line.Substring(0, 9) + _ 
          line.Substring(9).Replace(replaceMe, replacement)) 

       line = r.ReadLine() 
      End While 

     End Using 
    End Using 
End Sub 
+0

C#示例會幫助 - 我會嘗試將其映射到VB ...謝謝! – Prabhu

+0

您可能需要稍稍處理異常處理。如果文件丟失,這可能會失敗,因爲流是在try/catch塊之外定義的。你明白了。 –

+0

謝謝傑森... – Prabhu

2

通過提供的源代碼位置來判斷是9

C#代碼:

var res = s.Substring(0, 9) + s.Substring(9).Replace("?????", "xxxxx"); 

VB.NET:

Dim res As String = (s.Substring(0, 9) & s.Substring(9).Replace("?????", "xxxxx")) 

例VB.NET:

Using sr As StreamReader = New StreamReader("a.txt") 
     Using sw As StreamWriter = New StreamWriter("b.txt") 
      Dim line As String = Nothing 
      Do While (Not line = sr.ReadLine Is Nothing) 
       Dim res As String = (line.Substring(0, 9) & line.Substring(9).Replace("?????", "xxxxx")) 
       sw.WriteLine(res) 
      Loop 
     End Using 
    End Using 

例C#:

using (var sr = new StreamReader("a.txt")) 
{ 
    using (var sw = new StreamWriter("b.txt")) 
    { 
     string line = null; 
     while ((line = sr.ReadLine()) != null) 
     { 
      var res = line.Substring(0, 9) + line.Substring(9).Replace("?????", "xxxxx"); 
      sw.WriteLine(res); 
     } 
    } 
} 
+0

那麼只要讀取每一行併爲這些索引做一個字符串替換?有沒有必要轉換爲數組或任何正確的? – Prabhu

+0

對不起,如果我不清楚,但我不想取代所有出現的?????在線上(可能有多個)。我只想替換位置/索引10中出現的那個。 – Prabhu

+0

這取決於文件大小。如果它很小,例如'File.ReadAllText',則替換字符串,寫入輸出。如果文件很大,按行讀取/替換/書寫更合適。 –