【问题标题】:C# StringReader ClassC# StringReader 类
【发布时间】:2013-08-06 14:34:21
【问题描述】:

我有这个问题,我正在使用 StringReader 从文本框中查找特定单词,到目前为止效果很好,但是我需要找到一种方法来检查每一行中的特定单词与字符串数组。

以下代码有效:

string txt = txtInput.Text;
string user1 = "adam";
int users = 0;
int systems = 0;

using (StringReader reader = new StringReader(txt))
{
    while ((txt = reader.ReadLine()) != null)
    {
        if (txt.Contains(user1))
        {
            users++;
        }
    }
}

现在,我创建了一个字符串数组来存储多个字符串,但是 Contains 方法似乎只接受一个字符串。

string[] systemsarray = new string[] { "as400", "x500", "mainframe" };

if(txt.Contains(systemsarray))
{
    systems++;
}
// error message: cannot convert from string[] to string

有没有人知道如何做到这一点,或改进它的方法?

提前致谢。

【问题讨论】:

    标签: c# arrays stringreader


    【解决方案1】:

    如果您正在寻找该行中是否存在这些单词,请尝试:

    if(systemsarray.Any(word => txt.Contains(word)))
    {
        users++;
    }
    

    【讨论】:

    • 或者干脆if (systemsarray.Any(txt.Contains))
    • 很难确定 OP 想要什么,但如果他们需要计数,请将 Any 替换为 Count 并将其存储在 systems 中。
    • @Moo-Juice HocsanMoya 选择的答案实际上与这个答案相同,只是在一个循环中展开,而不是使用 LINQ 作为一个衬里。
    • 你好,我刚做了,对此我很抱歉。
    【解决方案2】:

    为什么不自己写一个扩展方法来做到这一点?

    public static class StringExtensionMethods
    {
        public static bool ContainsAny(this string self, params string[] toFind)
        {
            bool found = false;
            foreach(var criteria in toFind)
                {
                    if (self.Contains(criteria))
                    {
                        found = true;
                        break;
                    }
                };
    
            return found;
        }   // eo ContainsAny    
    }
    

    用法:

    string[] systemsarray = new string[] { "as400", "x500", "mainframe" };
    
    if(txt.ContainsAny(systemsarray))
    {
        systems++;
    }
    // error message: cannot convert from string[] to string
    

    【讨论】:

    • 谢谢,很有帮助!
    【解决方案3】:

    您需要从数组中提取每个项目:

    foreach (string item in systemsarray)
    {
     if(txt.Contains(item))
     {
        systems++;
     }
    }
    

    【讨论】:

    • @LuameLudik,很抱歉再次打扰,我想知道您知道如何摆脱重复项吗?我已经尝试了几件事但仍然无法正常工作,我创建了一个新的字符串数组并尝试删除重复项... String[] systems2 = new string[] {item}; IEnumerable distinctsystem = systems2.Distinct(); foreach (String theString in distinctsystem) { systems++; }
    【解决方案4】:

    如果您想要不区分大小写的搜索(as400 将匹配 AS400),您可以这样做

    if (systemsarray.Any(x => x.Equals(txt, StringComparison.OrdinalIgnoreCase)))
    {
        //systemsarray contains txt or TXT or TxT etc...
    }
    

    如果您想考虑这种情况,可以删除StringComparison.OrdinalIgnoreCase(或选择不同的枚举值)。

    【讨论】:

    • 您好,感谢您的帮助,我所做的是将所有文本转换为小写;像这样;字符串 txt = txtInput.Text.ToLower();但我会考虑到这一点,再次感谢!
    • @HocsanMoya - 不客气。作为旁注,不建议转换和检查小写字母。您通常应该使用上面的比较检查或将其转换为大写而不是more info
    • 嗨!谢谢,那样的话,我会听从你的建议的。
    猜你喜欢
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多