【问题标题】:How to determine if string contains specific substring ignoring the case sensitive [duplicate]如何确定字符串是否包含忽略大小写的特定子字符串[重复]
【发布时间】:2016-08-22 17:32:20
【问题描述】:

我想检查下面的字符串是否包含c#中的top/ TOP/toP/ Top/TOp/ Top。我的代码是这样的

string str = null;
        str = "CSharp Top11111 10 BOOKS";
        if (str.Contains("top") == true)
        {
            Console.WriteLine("The string Contains() 'TOP' ");
        }
        else
        {
            Console.WriteLine("The String does not Contains() 'TOP'");
        }

但只有当我的字符串包含'top'时它才返回true。对于所有其他情况,如何返回 true 呢?我知道这可能很简单,但我搜索了很多没有找到任何解决方案

【问题讨论】:

    标签: c#


    【解决方案1】:

    使用两者之一:.ToLower().ToUpper

    string str = null;
        str = "CSharp Top11111 10 BOOKS";
        if (str.ToLower().Contains("top") == true)
        {
            Console.WriteLine("The string Contains() 'TOP' ");
        }
        else
        {
            Console.WriteLine("The String does not Contains() 'TOP'");
        }
    

    【讨论】:

      【解决方案2】:

      无需任何转换:

      bool found = "My Name is".IndexOf("name", StringComparison.OrdinalIgnoreCase) >= 0;
      

      【讨论】:

        猜你喜欢
        • 2012-12-10
        • 1970-01-01
        • 2015-07-18
        • 2011-01-17
        • 2013-05-12
        • 2014-01-29
        • 2020-06-13
        • 2017-12-13
        • 1970-01-01
        相关资源
        最近更新 更多