读取文件时跳过单词/符号

本文关键字:单词 符号 文件 读取 | 更新日期: 2023-09-27 18:05:36

我正在制作一个小的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));

读取文件时跳过单词/符号

你可以用none来代替它们:

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;

您可以使用String.Replace将它们替换为none:

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

伙计们给出了很好的解决方案,我只是想添加另一个快速(使用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", ":", "'", ",");