C# 不区分大小写的“包含(字符串)”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/444798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Case insensitive 'Contains(string)'
提问by Boris Callens
Is there a way to make the following return true?
有没有办法使以下返回true?
string title = "ASTRINGTOTEST";
title.Contains("string");
There doesn't seem to be an overload that allows me to set the case sensitivity.. Currently I UPPERCASE them both, but that's just silly (by which I am referring to the i18nissues that come with up- and down casing).
似乎没有允许我设置区分大小写的过载.. 目前我将它们都大写,但这只是愚蠢的(我指的是上下大小写的i18n问题)。
UPDATE
This question is ancient and since then I have realized I asked for a simple answer for a really vast and difficult topic if you care to investigate it fully.
For most cases, in mono-lingual, English code bases thisanswer will suffice. I'm suspecting because most people coming here fall in this category this is the most popular answer.
Thisanswer however brings up the inherent problem that we can't compare text case insensitive until we know both texts are the same culture and we know what that culture is. This is maybe a less popular answer, but I think it is more correct and that's why I marked it as such.
更新
这个问题很古老,从那时起我意识到如果你想对一个非常庞大而困难的话题进行全面调查,我会要求一个简单的答案。
对于大多数情况,在单语、英语代码库中,这个答案就足够了。我怀疑是因为大多数来这里的人都属于这一类,这是最受欢迎的答案。然而,
这个答案带来了一个固有的问题,即在我们知道两个文本是相同的文化并且我们知道该文化是什么之前,我们无法比较不区分大小写的文本。这可能是一个不太受欢迎的答案,但我认为它更正确,这就是我将其标记为这样的原因。
采纳答案by Colonel Panic
To test if the string paragraph
contains the string word
(thanks @QuarterMeister)
测试字符串是否paragraph
包含字符串word
(感谢@QuarterMeister)
culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0
Where culture
is the instance of CultureInfo
describing the language that the text is written in.
描述文本所用语言culture
的实例在哪里CultureInfo
。
This solution is transparent about the definition of case-insensitivity, which is language dependent. For example, the English language uses the characters I
and i
for the upper and lower case versions of the ninth letter, whereas the Turkish language uses these characters for the eleventh and twelfth lettersof its 29 letter-long alphabet. The Turkish upper case version of 'i' is the unfamiliar character '?'.
这个解决方案对于不区分大小写的定义是透明的,它是语言相关的。例如,英语将字符I
和i
用于第九个字母的大写和小写版本,而土耳其语将这些字符用于其 29 个字母长的字母表中的第十一个和第十二个字母。'i' 的土耳其语大写版本是不熟悉的字符 '?'。
Thus the strings tin
and TIN
are the same word in English, but different words in Turkish. As I understand, one means 'spirit' and the other is an onomatopoeia word. (Turks, please correct me if I'm wrong, or suggest a better example)
因此,字符串tin
和在英语TIN
中是同一个词,但在土耳其语中是不同的词。据我了解,一个是“精神”的意思,另一个是象声词。(土耳其人,如果我错了,请纠正我,或者提出一个更好的例子)
To summarise, you can only answer the question 'are these two strings the same but in different cases' if you know what language the text is in. If you don't know, you'll have to take a punt. Given English's hegemony in software, you should probably resort to CultureInfo.InvariantCulture
, because it'll be wrong in familiar ways.
总而言之,如果您知道文本是什么语言,您只能回答“这两个字符串是否相同但在不同情况下”的问题。如果你不知道,你将不得不采取平底船。鉴于英语在软件方面的霸权,您可能应该求助于CultureInfo.InvariantCulture
,因为它会以熟悉的方式出错。
回答by Ed S.
You could always just up or downcase the strings first.
您始终可以先将字符串大写或小写。
string title = "string":
title.ToUpper().Contains("STRING") // returns true
Oops, just saw that last bit. A case insensitive compare would *
probably*
do the same anyway, and if performance is not an issue, I don't see a problem with creating uppercase copies and comparing those. I could have sworn that I once saw a case-insensitive compare once...
哎呀,刚看到最后一点。无论如何,不区分大小写的比较可能*
会*
做同样的事情,如果性能不是问题,我认为创建大写副本并比较它们没有问题。我可以发誓我曾经看过一次不区分大小写的比较...
回答by JaredPar
You could use the String.IndexOf Methodand pass StringComparison.OrdinalIgnoreCase
as the type of search to use:
您可以使用String.IndexOf 方法并将其StringComparison.OrdinalIgnoreCase
作为要使用的搜索类型传递:
string title = "STRING";
bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;
Even better is defining a new extension method for string:
更好的是为字符串定义一个新的扩展方法:
public static class StringExtensions
{
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source?.IndexOf(toCheck, comp) >= 0;
}
}
Note, that null propagation?.
is available since C# 6.0 (VS 2015), for older versions use
请注意,从 C# 6.0 (VS 2015) 开始,空传播?.
可用,对于旧版本使用
if (source == null) return false;
return source.IndexOf(toCheck, comp) >= 0;
USAGE:
用法:
string title = "STRING";
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);
回答by mkchandler
You can use IndexOf()
like this:
你可以这样使用IndexOf()
:
string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
// The string exists in the original
}
Since 0 (zero) can be an index, you check against -1.
由于 0(零)可以是索引,因此您可以对照 -1 进行检查。
The zero-based index position of value if that string is found, or -1 if it is not. If value is String.Empty, the return value is 0.
如果找到该字符串,则为 value 的从零开始的索引位置,否则为 -1。如果值为 String.Empty,则返回值为 0。
回答by Jed
Alternative solution using Regex:
使用正则表达式的替代解决方案:
bool contains = Regex.IsMatch("StRiNG to search", Regex.Escape("string"), RegexOptions.IgnoreCase);
回答by Andrew
StringExtension class is the way forward, I've combined a couple of the posts above to give a complete code example:
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;
}
}
回答by FeiBao 飞豹
One issue with the answer is that it will throw an exception if a string is null. You can add that as a check so it won't:
答案的一个问题是,如果字符串为空,它将引发异常。您可以将其添加为支票,以免:
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;
}
回答by mr.martan
Use this:
用这个:
string.Compare("string", "STRING", new System.Globalization.CultureInfo("en-US"), System.Globalization.CompareOptions.IgnoreCase);
回答by serhio
I know that this is not the C#, but in the framework (VB.NET) there is already such a function
我知道这不是C#,但在框架(VB.NET)中已经有这样的功能
Dim str As String = "UPPERlower"
Dim b As Boolean = InStr(str, "UpperLower")
C# variant:
C# 变体:
string myString = "Hello World";
bool contains = Microsoft.VisualBasic.Strings.InStr(myString, "world");
回答by takirala
This is clean and simple.
这是干净和简单的。
Regex.IsMatch(file, fileNamestr, RegexOptions.IgnoreCase)