2013-03-24 94 views
0

我正在製作一個小型C#應用程序,但我遇到了一個小問題。讀取文件時跳過文字/符號

我有一個純文本的.xml,我只需要第4行。

string filename = "file.xml"; 
if (File.Exists(filename)) 
{ 
    string[] lines = File.ReadAllLines(filename); 
    textBox1.Text += (lines[4]); 
} 

直到現在一切都很好,我唯一的問題是我必須從第四行刪除一些單詞和符號。

我的髒話和符號:

word 1 
: 
' 
, 

心中已經一直在尋找對谷歌,但是我無法找到C#什麼。 找到了VB的代碼,但我是新來的,我真的不知道如何轉換它,並使其工作。

Dim crlf$, badChars$, badChars2$, i, tt$ 
    crlf$ = Chr(13) & Chr(10) 
    badChars$ = "\/:*?""<>|"   ' For Testing, no spaces 
    badChars2$ = "\/: * ? "" < > |" ' For Display, has spaces 

    ' Check for bad characters 
For i = 1 To Len(tt$) 
    If InStr(badChars$, Mid(tt$, i, 1)) <> 0 Then 
    temp = MsgBox("A directory name may not contain any of the following" _ 
      & crlf$ & crlf$ & "  " & badChars2$, _ 
      vbOKOnly + vbCritical, _ 
      "Bad Characters") 
    Exit Sub 
    End If 
Next i 

謝謝。

固定:)

textBox1.Text += (lines[4] 
       .Replace("Word 1", String.Empty) 
      .Replace(":", String.Empty) 
      .Replace("'", String.Empty) 
      .Replace(",", String.Empty)); 
+0

'string.Replace'? – Matten 2013-03-24 10:22:13

+1

如果你的文件是XML文件,你真的,真的**應該把它解析爲XML。試試'XDocument.Load'。 – driis 2013-03-24 10:22:25

+0

檢查字符串。替換,謝謝。 --- XML的內容取自一個JS腳本WEB。 – rgerculy 2013-03-24 10:23:37

回答

2

您可以用什麼代替他們:

textBox1.Text += lines[4].Replace("word 1 ", string.Empty) 
         .Replace(":", string.Empty) 
         .Replace("'", string.Empty) 
         .Replace(",", string.Empty); 

或者創建一個數組要刪除的表達式,並全部替換爲無。

string[] wordsToBeRemoved = { "word 1", ":", "'", "," }; 

string result = lines[4]; 
foreach (string toBeRemoved in wordsToBeRemoved) { 
    result = result.Replace(toBeRemoved, string.Empty); 
} 
textBox1.Text += result; 
+0

修正:)謝謝。 – rgerculy 2013-03-24 10:29:29

+0

有什麼方法可以刪除空間嗎? – rgerculy 2013-03-24 10:44:18

+0

@rgerculy當然,只需在'wordsToBeRemoved'中加入''「''即可。 – antonijn 2013-03-24 10:45:05

1

您可以使用String.Replace用什麼來取代它們:

textBox1.Text += (lines[4] 
      .Replace("Word 1", String.Empty) 
      .Replace(":", String.Empty) 
      .Replace("'", String.Empty) 
      .Replace(",", String.Empty)); 
+0

謝謝!工作:) – rgerculy 2013-03-24 10:26:15

0

你們給了很好的解決方案,我只是想添加一個快速(使用StringBuilder),方便(使用擴展方法的語法和params作爲值)解決方案

public static string RemoveStrings(this string str, params string[] strsToRemove) 
{ 
    var builder = new StringBuilder(str); 
    strsToRemove.ToList().ForEach(v => builder.Replace(v, "")); 
    return builder.ToString(); 
} 

現在你可以

string[] lines = File.ReadAllLines(filename); 
textBox1.Text += lines[4].RemoveStrings("word 1", ":", "'", ","); 
+0

感謝您的回答,但我想要一些非常簡單的東西來理解我的自我:) – rgerculy 2013-03-24 10:56:41

+0

@rgerculy在方法實現中有3個簡短的代碼行,您可以更簡單地獲得? – 2013-03-24 11:02:39

+0

True ...但是第二行「strsToRemove.ToList()。ForEach(v => builder.Replace(v,」「));」令我困惑。我是新人,我必須學習很多東西。 – rgerculy 2013-03-24 11:15:48

相關問題