【问题标题】:Remove unwanted characters from a List using C# [closed]使用 C# 从列表中删除不需要的字符 [关闭]
【发布时间】:2012-12-18 08:07:14
【问题描述】:

我有一个多行文本框,我可以将任何文本项的列表粘贴到其中,如下所示:

555-555-1212
I want's a lemon's.
google.com
1&1 Hosting

我旁边还有一个文本框,我可以添加逗号分隔的字符串,我想从列表中的所有项目中删除这些字符串,如下所示:

-,$,!,@,#,$,%,^,&,*,(,),.com,.net,.org

我试图弄清楚如何从我的文本框列表中的每个字符串中清除每个字符串(或我放入第二个文本框中的任何其他字符串)。

有什么想法吗?我知道如何将列表变成列表字符串,但不确定如何清理该字符串。

这是我目前所拥有的......但我得到了红色的波浪线:

List<string> removeChars = new List<string>(textBox6.Text.Split(','));                 
for (int i = 0; i < sortBox1.Count; i++)
{
    sortBox1[i] = Regex.Replace(sortBox1[i], removeChars, "").Trim();
}

【问题讨论】:

  • 我想出了如何将多行文本框放入列表中,并将已清理的字符串放入列表中,但不知道如何清理。
  • 解决问题的简单方法是使用msdn.microsoft.com/en-us/library/system.string.replace.aspx C# 已经为几乎所有基本问题准备好了灵魂。您应该花时间阅读 C# 书籍。

标签: c# arrays list trim


【解决方案1】:
private void button1_Click(object sender, EventArgs e)
{
    string[] lines = new string[] { "555-555-1212", "I want's a lemon's.", "google.com", "1&1 Hosting" };
    string[] removables = textBox1.Text.Split(',');
    string[] newLine = new string[lines.Count()];

    int i = 0;
    foreach (string line in lines)
    {
        newLine[i] = line;
        foreach (string rem in removables)
        {
            while(newLine[i].Contains(rem))
                newLine[i] = newLine[i].Remove(newLine[i].IndexOf(rem), rem.Length);
        }
        MessageBox.Show(newLine[i]);
        i++;
    }
}

结果:

5555551212
我想要一个柠檬
谷歌
1&1 托管

【讨论】:

    【解决方案2】:

    Textbox.Lines 中的每一行的不需要列表中的每个字符串使用 String.Replace

    string[] replaceStrings = txtUnwanted.Text.Split(',');
    List<string> lines = new List<string>(textBox1.Lines);
    for (int i = 0; i < lines.Count; i++)
        foreach (string repl in replaceStrings)
            lines[i] = lines[i].Replace(repl, "");
    

    编辑:这是一个演示:http://ideone.com/JQl79k(没有 Windows 控件,因为 ideone 不支持它)

    【讨论】:

    • 工作完美,蒂姆。非常感谢!
    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多