C# 不区分大小写';包含(字符串)和#x27;
有没有办法使下面的返回为真C# 不区分大小写';包含(字符串)和#x27;,c#,string,contains,case-insensitive,C#,String,Contains,Case Insensitive,有没有办法使下面的返回为真 string title = "ASTRINGTOTEST"; title.Contains("string"); 似乎没有让我设置区分大小写的重载。。目前我把它们都大写了,但这太傻了(我指的是上下两种情况下出现的问题) 更新 这个问题由来已久,从那时起,我意识到,如果你愿意全面调查的话,我要求的是一个非常广泛和困难的话题的简单答案。 在大多数情况下,以单语、英语代码为基础的答案就足够了。我怀疑是因为大多数来这里的人都属于这一类。这是最流行的答案。 然而,这个答案带
string title = "ASTRINGTOTEST";
title.Contains("string");
似乎没有让我设置区分大小写的重载。。目前我把它们都大写了,但这太傻了(我指的是上下两种情况下出现的问题)
更新这个问题由来已久,从那时起,我意识到,如果你愿意全面调查的话,我要求的是一个非常广泛和困难的话题的简单答案。
在大多数情况下,以单语、英语代码为基础的答案就足够了。我怀疑是因为大多数来这里的人都属于这一类。这是最流行的答案。
然而,这个答案带来了一个固有的问题,即在我们知道两个文本都是相同的文化,并且我们知道文化是什么之前,我们不能比较不区分大小写的文本。这可能是一个不太受欢迎的答案,但我认为它更正确,这就是为什么我将其标记为这样。您总是可以先将字符串的大小写向上或向下
string title = "string":
title.ToUpper().Contains("STRING") // returns true
哎呀,刚刚看到最后一点。不区分大小写的比较将*
很可能*
也会这样做,如果性能不是问题,我认为创建大写副本并比较它们不会有问题。我可以发誓,我曾经看到过一次不区分大小写的比较…您可以使用and pass作为要使用的搜索类型:
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);
您可以像这样使用IndexOf()
:
string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
// The string exists in the original
}
string s="AbcdEf";
if(s.ToLower().Contains("def"))
{
Console.WriteLine("yes");
}
因为0(零)可以是一个索引,所以可以对照-1进行检查
如果找到该字符串,则值的从零开始的索引位置,或-1
如果不是。如果值为String.Empty,则返回值为0
使用正则表达式的替代解决方案:
bool contains = Regex.IsMatch("StRiNG to search", Regex.Escape("string"), RegexOptions.IgnoreCase);
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;
}
}
公共静态类StringExtensions
{
///
///允许不区分大小写的检查
///
公共静态bool包含(此字符串源、字符串toCheck、字符串比较comp)
{
返回source.IndexOf(toCheck,comp)>=0;
}
}
答案的一个问题是,如果字符串为空,它将抛出异常。您可以将其添加为支票,这样它就不会:
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;
}
使用以下命令:
string.Compare("string", "STRING", new System.Globalization.CultureInfo("en-US"), System.Globalization.CompareOptions.IgnoreCase);
我知道这不是C#,但在框架(VB.NET)中已经有这样一个函数
Dim str As String = "UPPERlower"
Dim b As Boolean = InStr(str, "UpperLower")
C#变体:
这既干净又简单。
Regex.IsMatch(file, fileNamestr, RegexOptions.IgnoreCase)
测试字符串
段落
是否包含字符串单词
(谢谢@QuarterMeister)
其中,文化
是描述文本所用语言的实例
此解决方案对大小写不敏感的定义是透明的,它依赖于语言。例如,英语使用字符I
和I
表示第九个字母的大写和小写版本,而土耳其语使用这些字符表示其29个字母的大写和小写版本。土耳其语大写的“i”是不熟悉的字符“İ”
因此,字符串tin
和tin
在英语中是相同的单词,但在土耳其语中是不同的单词。据我所知,一个意思是“精神”,另一个是拟声词。(土耳其人,如果我错了,请纠正我,或者举个更好的例子)
总而言之,如果您知道文本使用的语言,您只能回答“这两个字符串是否相同但情况不同”的问题。如果你不知道,你就得打个平底船。鉴于英语在软件领域的霸主地位,你可能应该求助于,因为它在熟悉的方面是错误的。使用正则表达式是一种直接的方法:
Regex.IsMatch(title, "string", RegexOptions.IgnoreCase);
如果您关心国际化(或者可以重新实现国际化),那么VisualBasic程序集的
InStr
方法是最好的。查看it 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);
}
OrdinalingOrecase、CurrentCultureInogoreCase或InvariantCultureInogoreCase? 由于缺少这一点,以下是关于何时使用哪一种的一些建议: 磁盘操作系统
- 使用
进行比较 作为区域性不可知字符串匹配的安全默认值StringComparison.OrdinalIgnoreCase
- 使用
比较 为了提高速度StringComparison.ordinallingorecase
- 使用
字符串操作 向用户显示输出时StringComparison.CurrentCulture-based
- 基于不变量切换当前使用的字符串操作
当比较为
语言上无关的(例如象征性的)李> - 使用
而不是ToUpperInvariant
时 规范化字符串以进行比较ToLowerInvariant
- 对不显式执行的字符串操作使用重载 或隐式指定字符串比较机制
- 使用基于字符串的
StringComparison.InvariantCulture
大多数情况下的操作;少数例外情况之一是
保留有语言意义但文化不可知的数据
根据这些规则,您应该使用:
string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.[YourDecision]) != -1)
{
// The string exists in the original
}
而[你的决定]取决于上面的建议
来源链接:就像这样:
string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
// The string exists in the original
}
string s="AbcdEf";
if(s.ToLower().Contains("def"))
{
Console.WriteLine("yes");
}
这与这里的其他示例非常相似,但我决定将enum简化为bool,primary,因为其他替代方案是
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) )
....
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);
if ("strcmpstring1".IndexOf(Convert.ToString("strcmpstring2"), StringComparison.CurrentCultureIgnoreCase) >= 0){return true;}else{return false;}
title.ToLower().Contains("string");//of course "string" is lowercase.
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
}
string yourStringForCheck= "abc";
string stringInWhichWeCheck= "Test abc abc";
bool isContained = stringInWhichWeCheck.ToLower().IndexOf(yourStringForCheck.ToLower()) > -1;
string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
// contains
}
string title = "STRING";
bool contains = title.ToLower().Contains("string")
Regex.IsMatch(title, "string", RegexOptions.IgnoreCase);
"Test".Contains("test", System.StringComparison.CurrentCultureIgnoreCase);
public static bool ContainsIgnoreCase(this string paragraph, string word)
{
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0;
}
title.ToLower().Contains("String".ToLower())
public static bool ContainsIgnoreCase(this string source, string substring)
{
return source?.IndexOf(substring ?? "", StringComparison.OrdinalIgnoreCase) >= 0;
}
public static class VStringExtensions
{
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
if (toCheck == null)
{
throw new ArgumentNullException(nameof(toCheck));
}
if (source.Equals(string.Empty))
{
return false;
}
if (toCheck.Equals(string.Empty))
{
return true;
}
return source.IndexOf(toCheck, comp) >= 0;
}
}
public bool Contains (string value, StringComparison comparisonType);
string title = "ASTRINGTOTEST";
title.Contains("string", StringComparison.InvariantCultureIgnoreCase);