不区分大小写的“包含(字符串)”

有没有办法使以下返回为真?

string title = "ASTRINGTOTEST";
title.Contains("string");

似乎没有允许我设置大小写敏感度的重载。.目前我都将它们都大写,但这只是愚蠢的(我指的是上下外壳附带的i18n问题)。

更新
这个问题是古老的,从那时起,我意识到如果您希望进行全面调查,我会为一个非常广泛且困难的主题要求一个简单的答案。
在大多数情况下,在单语的英语代码库中, 答案就足够了。 我很怀疑,因为大多数来这里的人都属于这一类,这是最受欢迎的答案。
但是, 这个答案提出了一个固有的问题,即我们无法区分不区分大小写的文本,直到我们知道两个文本是相同的文化并且我们知道该文化是什么。 这可能是一个不太受欢迎的答案,但我认为它更正确,这就是为什么我将其标记为这样。


#1楼

这是干净而简单的。

Regex.IsMatch(file, fileNamestr, RegexOptions.IgnoreCase)

#2楼

测试字符串paragraph包含字符串word (感谢@QuarterMeister)

culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0

其中culture是实例CultureInfo描述,该文本用的语言。

该解决方案对于不区分大小写的定义是透明的, 该定义取决于语言 。 例如,英语使用第九个字母的大写和小写字母Ii ,而土耳其语使用29个字母长的字母的第十一和第十二个字母。 土耳其语的大写版本“ i”是一个陌生的字符“İ”。

因此,字符串tinTIN 在英语中是相同的词,但是在土耳其语中是不同的词。 据我了解,一种是“精神”,另一种是拟声词。 (特克斯,如果我错了,请纠正我,或者提出一个更好的例子)

总而言之, 如果您知道文本所用的语言 ,则只能回答“这两个字符串相同但在不同情况下” 的问题 。 如果您不知道,则必须平底锅。 鉴于英语在软件方面的霸权地位,您可能应该诉诸CultureInfo.InvariantCulture ,因为用熟悉的方式会出错。


#3楼

使用RegEx是执行此操作的直接方法:

Regex.IsMatch(title, "string", RegexOptions.IgnoreCase);

#4楼

如果您担心国际化(或者可以重新实现),则VisualBasic程序集的InStr方法是最好的。 查看其中的dotNeetPeek不仅显示了大写和小写字母,还显示了假名类型以及全角和半角字符(大多数情况下适用于亚洲语言,尽管罗马字母也有全角版本) )。 我跳过了一些细节,但是请查看私有方法InternalInStrText

private static int InternalInStrText(int lStartPos, string sSrc, string sFind)
{
  int num = sSrc == null ? 0 : sSrc.Length;
  if (lStartPos > num || num == 0)
    return -1;
  if (sFind == null || sFind.Length == 0)
    return lStartPos;
  else
    return Utils.GetCultureInfo().CompareInfo.IndexOf(sSrc, sFind, lStartPos, CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth);
}

#5楼

顺序忽略案例,当前文化忽略案例还是不变文化忽略案例?

由于缺少此功能,因此以下是有关何时使用哪个的一些建议:

多斯

  • 使用StringComparison.OrdinalIgnoreCase进行比较,作为与区域性无关的字符串匹配的安全默认值。
  • 使用StringComparison.OrdinalIgnoreCase比较可以提高速度。
  • 在向用户显示输出时,请使用StringComparison.CurrentCulture-based字符串操作。
  • 在比较时,将基于不变文化的字符串操作的当前使用切换为使用非语言的StringComparison.OrdinalStringComparison.OrdinalIgnoreCase
    在语言上不相关(例如符号)。
  • 标准化字符串进行比较时,请使用ToUpperInvariant而不是ToLowerInvariant

不要

  • 对没有显式或隐式指定字符串比较机制的字符串操作使用重载。
  • 使用基于StringComparison.InvariantCulture的字符串
    大多数情况下的操作; 少数例外之一是
    保留语言上有意义但与文化无关的数据。

根据这些规则,您应该使用:

string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.[YourDecision]) != -1)
{
    // The string exists in the original
}

而[您的决定]取决于上面的建议。

来源链接: http : //msdn.microsoft.com/en-us/library/ms973919.aspx


#6楼

像这样:

string s="AbcdEf";
if(s.ToLower().Contains("def"))
{
    Console.WriteLine("yes");
}

#7楼

这与这里的其他示例非常相似,但是我决定将枚举简化为bool,因为主要不需要其他替代方法。 这是我的示例:

public static class StringExtensions
{
    public static bool Contains(this string source, string toCheck, bool bCaseInsensitive )
    {
        return source.IndexOf(toCheck, bCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0;
    }
}

用法类似于:

if( "main String substring".Contains("SUBSTRING", true) )
....

#8楼

使用Regex的替代解决方案:

bool contains = Regex.IsMatch("StRiNG to search", Regex.Escape("string"), RegexOptions.IgnoreCase);

#9楼

这里的技巧是查找字符串,忽略大小写,但要使其完全相同(大小写相同)。

 var s="Factory Reset";
 var txt="reset";
 int first = s.IndexOf(txt, StringComparison.InvariantCultureIgnoreCase) + txt.Length;
 var subString = s.Substring(first - txt.Length, txt.Length);

输出为“重置”


#10楼

if ("strcmpstring1".IndexOf(Convert.ToString("strcmpstring2"), StringComparison.CurrentCultureIgnoreCase) >= 0){return true;}else{return false;}

#11楼

您可以使用string.indexof ()函数。 这将不区分大小写


#12楼

StringExtension类是前进的方向,我结合了上面的几篇文章,给出了完整的代码示例:

public static class StringExtensions
{
    /// <summary>
    /// Allows case insensitive checks
    /// </summary>
    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source.IndexOf(toCheck, comp) >= 0;
    }
}

#13楼

title.ToLower().Contains("string");//of course "string" is lowercase.

#14楼

答案的一个问题是,如果字符串为null,它将引发异常。 您可以将其添加为支票,这样就不会:

public static bool Contains(this string source, string toCheck, StringComparison comp)
{
    if (string.IsNullOrEmpty(toCheck) || string.IsNullOrEmpty(source))
        return true;

    return source.IndexOf(toCheck, comp) >= 0;
} 

#15楼

您总是可以先将字符串大写或小写。

string title = "string":
title.ToUpper().Contains("STRING")  // returns true

糟糕,刚刚看到了最后一点。 不区分大小写的比较将*大概*做同样无论如何,如果性能是不是一个问题,我没有看到一个问题与创建大写副本和比较的。 我本该发誓我曾经看到一个不区分大小写的比较...


#16楼

您可以使用String.IndexOf方法并传递StringComparison.OrdinalIgnoreCase作为要使用的搜索类型:

string title = "STRING";
bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;

更好的是为字符串定义新的扩展方法:

public static class StringExtensions
{
    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source?.IndexOf(toCheck, comp) >= 0;
    }
}

注意, 零传播 ?. 自C#6.0(VS 2015)开始可用,供较旧版本使用

if (source == null) return false;
return source.IndexOf(toCheck, comp) >= 0;

用法:

string title = "STRING";
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);

#17楼

您可以像这样使用IndexOf()

string title = "STRING";

if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
    // The string exists in the original
}

由于0(零)可以作为索引,因此请对照-1进行检查。

MSDN

如果找到该字符串,则从零开始的索引位置,否则为-1。 如果value为String.Empty,则返回值为0。


#18楼

public static class StringExtension
{
    #region Public Methods

    public static bool ExContains(this string fullText, string value)
    {
        return ExIndexOf(fullText, value) > -1;
    }

    public static bool ExEquals(this string text, string textToCompare)
    {
        return text.Equals(textToCompare, StringComparison.OrdinalIgnoreCase);
    }

    public static bool ExHasAllEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index]) == false) return false;
        return true;
    }

    public static bool ExHasEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index])) return true;
        return false;
    }

    public static bool ExHasNoEquals(this string text, params string[] textArgs)
    {
        return ExHasEquals(text, textArgs) == false;
    }

    public static bool ExHasNotAllEquals(this string text, params string[] textArgs)
    {
        for (int index = 0; index < textArgs.Length; index++)
            if (ExEquals(text, textArgs[index])) return false;
        return true;
    }

    /// <summary>
    /// Reports the zero-based index of the first occurrence of the specified string
    /// in the current System.String object using StringComparison.InvariantCultureIgnoreCase.
    /// A parameter specifies the type of search to use for the specified string.
    /// </summary>
    /// <param name="fullText">
    /// The string to search inside.
    /// </param>
    /// <param name="value">
    /// The string to seek.
    /// </param>
    /// <returns>
    /// The index position of the value parameter if that string is found, or -1 if it
    /// is not. If value is System.String.Empty, the return value is 0.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    /// fullText or value is null.
    /// </exception>
    public static int ExIndexOf(this string fullText, string value)
    {
        return fullText.IndexOf(value, StringComparison.OrdinalIgnoreCase);
    }

    public static bool ExNotEquals(this string text, string textToCompare)
    {
        return ExEquals(text, textToCompare) == false;
    }

    #endregion Public Methods
}

#19楼

如果要检查传递的字符串是否在字符串中,则有一个简单的方法。

string yourStringForCheck= "abc";
string stringInWhichWeCheck= "Test abc abc";

bool isContained = stringInWhichWeCheck.ToLower().IndexOf(yourStringForCheck.ToLower()) > -1;

如果包含或不包含字符串,则返回此布尔值


#20楼

这些是最简单的解决方案。

  1. 按索引

     string title = "STRING"; if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1) { // contains } 
  2. 通过改变大小写

     string title = "STRING"; bool contains = title.ToLower().Contains("string") 
  3. 通过正则表达式

     Regex.IsMatch(title, "string", RegexOptions.IgnoreCase); 

#21楼

仅限.NET Core 2.0+(截至目前)

自2.0版以来,.NET Core有两种方法可以解决此问题:

  • String.Contains(Char, StringComparison
  • String.Contains(String, StringComparison

例:

"Test".Contains("test", System.StringComparison.CurrentCultureIgnoreCase);

随着时间的流逝,它们可能会进入.NET标准,并从那里进入基类库的所有其他实现。


#22楼

只是基于此处的答案,您可以创建一个字符串扩展方法以使其更加人性化:

    public static bool ContainsIgnoreCase(this string paragraph, string word)
    {
        return CultureInfo.CurrentCulture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0;
    }

#23楼

用这个:

string.Compare("string", "STRING", new System.Globalization.CultureInfo("en-US"), System.Globalization.CompareOptions.IgnoreCase);

#24楼

我知道这不是C#,但是在框架(VB.NET)中已经有这样的功能

Dim str As String = "UPPERlower"
Dim b As Boolean = InStr(str, "UpperLower")

C#变体:

string myString = "Hello World";
bool contains = Microsoft.VisualBasic.Strings.InStr(myString, "world");
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值