tibin mathew
tibin mathew

Reputation: 2084

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

Upvotes: 2

Views: 370

Answers (5)

Sukasa
Sukasa

Reputation: 1700

if (string1.Contains(string2)) {
    //Your code here
}

Upvotes: 6

hhravn
hhravn

Reputation: 1761

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.

Upvotes: 2

Joey
Joey

Reputation: 354874

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))
{
    // ...
}

Upvotes: 11

AceMark
AceMark

Reputation: 729

string1.Contains(string2) best answers this.

Upvotes: 2

womp
womp

Reputation: 116987

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
}

Upvotes: 6

Related Questions