C# 中的字符串比较

发布于 2024-08-14 04:02:00 字数 219 浏览 1 评论 0原文

我想比较两个字符串的任何匹配

,即;

我的两个字符串是

string1 = "hi i'm tibinmathew @ i'm fine";

string2 = "tibin";

我想比较上面的两个字符串。

如果找到任何匹配项,我必须执行一些语句。

我想在 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#. How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

臻嫒无言 2024-08-21 04:02:00

比如下面这样的?

string1 = "hi i'm tibinmathew @ i'm fine";
string2 = "tibin";

if (string1.Contains(string2))
{
    // ...
}

对于简单的子字符串,这是可行的。还有诸如 StartsWithEndsWith 之类的方法。

对于更复杂的匹配,您可能需要正则表达式:

Regex re = new Regex(@"hi.*I'm fine", RegexOptions.IgnoreCase);

if (re.Match(string1))
{
    // ...
}

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.

For more elaborate matches you may need regular expressions:

Regex re = new Regex(@"hi.*I'm fine", RegexOptions.IgnoreCase);

if (re.Match(string1))
{
    // ...
}
勿忘初心 2024-08-21 04:02:00
if (string1.Contains(string2)) {
    //Your code here
}
if (string1.Contains(string2)) {
    //Your code here
}
哆兒滾 2024-08-21 04:02:00

看起来您只是想查看第一个字符串是否有与第二个字符串匹配的子字符串(无论在其中的任何位置)。你可以这样做:

if (string1.Contains(string2))
{
   // Do stuff
}

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
}
清风疏影 2024-08-21 04:02:00

string1.Contains(string2) 最好地回答这个问题。

string1.Contains(string2) best answers this.

穿越时光隧道 2024-08-21 04:02:00

如果您还想要匹配的位置,您可以执行正则表达式,或者

int index = string1.IndexOf(string2, StringComparison.OrdinalIgnoreCase);

如果 string2 不在 string1 中则简单地返回 -1,忽略大小写。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文