[英]C# String Comparison
I am making an application i have to compare two strings for a specific word 我正在申请,我必须比较一个特定单词的两个字符串
for eg 例如
string a="abc";
string b="abcController";
I have to compare a
and b
to match abc 我必须比较a
和b
才能匹配abc
I am using Equals
or CompareTo
but these are not working 我正在使用Equals
或CompareTo
但是它们不起作用
In the simplest fashion, you can use the Contains
method : 以最简单的方式,您可以使用Contains
方法 :
var a = "abc";
var b = "abcSOMDH";
var c = b.Contains(a);
This method performs an ordinal (case-sensitive and culture-insensitive) comparison. 此方法执行序数比较(区分大小写和不区分文化)。 The search begins at the first character position of this string and continues through the last character position. 搜索从该字符串的第一个字符位置开始,并一直持续到最后一个字符位置。
string str1 = "abc";
string str2 = "abcController";
if(str2.Contains(str1))
...
Use: 采用:
string a = "abc";
string b = "abcdefsdfs";
if (a.Contains(b) || b.Contains(a))
//DO SOMETHING
使用string.Contains
方法
b.Contains(a)
An alternative to Contains
would be IndexOf
Contains
的替代方法是IndexOf
var a = "abc";
var b = "abcSOMDH";
var c = b.IndexOf(a) >= 0; // returns TRUE if b occurs in a
var d = b.IndexOf(a, StringComparison.OrdinalIgnoreCase); // same but case insensitive
Description from MSDN : 来自MSDN的描述:
Reports the zero-based index of the first occurrence of one or more characters,
or the first occurrence of a string, within this string. The method returns -1 if
the character or string is not found in this instance.
Just a quick comment on the answers above: it's not a good idea to use ToLowerInvariant() or ToUpperInvariant(). 请快速回答以上答案:使用ToLowerInvariant()或ToUpperInvariant()不是一个好主意。 Both of these calls have to create brand new strings, upper or lower case, before comparison. 比较之前,这两个调用都必须创建全新的大写或小写字符串。
Instead, use an overload of the Contains() method that accepts an IEqualityComparer, like this: 而是使用包含IEqualityComparer的Contains()方法的重载,如下所示:
string stringA; stringA.Contains(stringB, StringComparer.CurrentCultureIgnoreCase);
This will do a case-insensitive comparison without allocating memory and copying the strings around. 这将进行不区分大小写的比较,而无需分配内存和复制字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.