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
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.
ToUpperInvariant prior to checking.b.ToLowerInvariant().Contains(a.ToLowerInvariant())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.
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.