[英]String comparing in c#
I want to compare two strings for any match 我想比较任何匹配的两个字符串
ie; 即;
my two string are 我的两个字符串是
string1 = "hi i'm tibinmathew @ i'm fine";
string2 = "tibin";
I want to compare the above two string. 我想比较上面的两个字符串。
If there is any match found i have to execute some statements. 如果发现任何匹配,我必须执行一些陈述。
I want to do this in c#. 我想在c#中这样做。 How can I do this? 我怎样才能做到这一点?
Such as the following? 如下?
string1 = "hi i'm tibinmathew @ i'm fine";
string2 = "tibin";
if (string1.Contains(string2))
{
// ...
}
For simple substrings this works. 对于简单的子串,这是有效的。 There are also methods like StartsWith
and EndsWith
. 还有像StartsWith
和EndsWith
这样的方法。
For more elaborate matches you may need regular expressions: 对于更精细的匹配,您可能需要正则表达式:
Regex re = new Regex(@"hi.*I'm fine", RegexOptions.IgnoreCase);
if (re.Match(string1))
{
// ...
}
It looks like you're just wanting to see if the first string has a substring that matches the second string, anywhere at all inside it. 看起来你只是想看看第一个字符串是否有一个匹配第二个字符串的子字符串,在它里面的任何地方。 You can do this: 你可以这样做:
if (string1.Contains(string2))
{
// Do stuff
}
if (string1.Contains(string2)) {
//Your code here
}
string1.Contains(string2)
最好的答案。
If you want the position of the match as well, you could either do the regex, or simply 如果你想要匹配的位置,你可以做正则表达式,或者只是
int index = string1.IndexOf(string2, StringComparison.OrdinalIgnoreCase);
returns -1 if string2 is not in string1, ignoring casing. 如果string2不在string1中,则返回-1,忽略大小写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.