Kavitha
Kavitha

Reputation: 1467

How to compare string with another string using c#

I have a situation where i don't want to compare total string length to other string .

Example:

string MainString = "Deanna Ecker";

string SearchString = "Ecker Designs";

int value = MainString.IndexOf(SearchString);

here it is searching with whole string. but i need to find any word in MainString. not with whole string..

Let me know how is this possible.

Upvotes: 3

Views: 138

Answers (3)

Zain Ul Abidin
Zain Ul Abidin

Reputation: 2710

you can convert your string to a char array then search each character via looping from all characters such that

public bool MatchString(string first,string second)
{
  char[] ch1=first.ToCharArray();
  char[] ch2=second.ToCharArray();
  bool match=false;
  for(int i=0 ; i<ch1.length ; i++)
   {
      for(int j=0 ; j<ch2.length ; j++)
       {
             if(ch2[j]==ch[i])
              {
                match=true;
                break;
              } 
       }
   }
 return match;
}

Upvotes: 1

Norris
Norris

Reputation: 2238

Try: var wordMatch = MainString.Split(' ').Intersect(SearchString.Split(' ')).Any();

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66499

If case-sensitivity is not an issue, you could split both strings by the space, then intersect the two lists to see if there are any matches:

var foundWords = MainString.Split(' ').Intersect(SearchString.Split(' '));

Or if you only want to know if a word was found:

var isMatch = MainString.Split(' ').Intersect(SearchString.Split(' ')).Any();

Upvotes: 8

Related Questions