0

我正在制作一个小型 C# 应用程序,但我遇到了一个小问题。

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

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

到目前为止一切都很好,我唯一的问题是我必须从第 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));
4

3 回答 3

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;
于 2013-03-24T10:25:02.077 回答
1

你可以用String.Replace什么来代替它们:

textBox1.Text += (lines[4]
            .Replace("Word 1", String.Empty)
            .Replace(":", String.Empty)
            .Replace("'", String.Empty)
            .Replace(",", String.Empty));
于 2013-03-24T10:24:07.450 回答
0

Guys gave good solutions, I just want to add another fast (using StringBuilder) and convenient (using Extension method syntax and params as values) solution

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();
}

now you can

string[] lines = File.ReadAllLines(filename);
textBox1.Text += lines[4].RemoveStrings("word 1", ":", "'", ",");
于 2013-03-24T10:31:02.333 回答