Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

c# - 不区分大小写的“包含(字符串)”(Case insensitive 'Contains(string)')

Is there a way to make the following return 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 i18n issues 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 this answer will suffice.

(在大多数情况下,在单语的英语代码库中, 答案就足够了。)

I'm suspecting because most people coming here fall in this category this is the most popular answer.

(我很怀疑,因为大多数来这里的人都属于这一类,这是最受欢迎的答案。)
This answer 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.

(这可能是一个不太受欢迎的答案,但我认为它更正确,这就是为什么我将其标记为这样。)

  ask by Boris Callens translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use the String.IndexOf Method and 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...