0

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

I am using Equals or CompareTo but these are not working

6 Answers 6

5

In the simplest fashion, you can use the Contains method:

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks It worked for me, but how can i apply it for case insensitive, means if a="abc" and b="Abc" it should still match correctly
You can convert both strings ToUpperInvariant prior to checking.
b.ToLowerInvariant().Contains(a.ToLowerInvariant())
I would suggest using the overload for Contains for which you can supply a StringComparer rether that creating a new string with ToUpperInvariant: bool c = b.Contains(a, StringComparer.OrdinalIgnoreCase);
3
string str1 = "abc";
string str2 = "abcController";
if(str2.Contains(str1))
     ...

Comments

3

Use:

 string a = "abc";
 string b = "abcdefsdfs";
 if (a.Contains(b) || b.Contains(a))
     //DO SOMETHING

Comments

2

Use string.Contains method

b.Contains(a)

Comments

1

An alternative to Contains would be 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:

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.

Comments

1

Just a quick comment on the answers above: it's not a good idea to use ToLowerInvariant() or 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:

string stringA; stringA.Contains(stringB, StringComparer.CurrentCultureIgnoreCase);

This will do a case-insensitive comparison without allocating memory and copying the strings around.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.