【问题标题】:Checking if a string contains a particular word检查字符串是否包含特定单词
【发布时间】:2013-12-23 14:02:26
【问题描述】:

我想把所有不包含“时间”这个词的词放在一个组合框中。

我试过了:

foreach (string stt in LTypes)
{
    //if the stat name does not contains TIME
    //Only then we add it to the combobox.

    if (!stt.Contains("Time"))
    { 
        tcomboBox1.Items.Add(stt);    
    }
}

但上述方法不起作用。 不起作用我的意思是包含“时间”的单词也被插入到组合框中。

我哪里做错了?

【问题讨论】:

  • 我想你忘了提到这些的大小写方式不同。我错了吗? Time 与 time 不同。
  • 是你填充组合框的那个地方吗?您还可以提供添加了Time 的示例字符串吗?
  • 什么是LTypes?运行上面的代码会发生什么?
  • LTypes 显然是一个 IEnumerable 字符串集合...

标签: c# combobox string-matching


【解决方案1】:

我们可以从您的代码和问题描述中看到,匹配失败(由于大小写不同)或您的组合框被一遍又一遍地填充。

试试这个:

//remember to clear your combobox if it is already populated!
tcomboBox1.Items.Clear(); 
foreach (string stt in LTypes)
{
    //setting string to lower/upper case will let you match any occurence of your word
    if (!stt.ToLowerCase().Contains("time"))
    { 
        tcomboBox1.Items.Add(stt);    
    }
}

【讨论】:

    【解决方案2】:

    您可以将IndexOf 与StringComparision.OrdinalIngoreCase 一起使用

    if (!(stt.IndexOf("Time", StringComparision.OrdinalIngoreCase) >=0))
    

    【讨论】:

      【解决方案3】:

      可能是大小写问题。

      试试这个:

      if (!stt.ToUpperInvariant().Contains("TIME"))
      

      不管大小写,这都会起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-20
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多