How do I search for a word in a string (just a word)?

I want to find a string for a word.

However, I don't want to get the result if the search word is inside another word. it

  • I want this to return the number 7 (index of the letter f):

    findWord ("Potato for you", "for")
  • but I want this to return -1 (i.e. not found)

    findWord ("Potato for you", "or")

If I use IndexOf

, it finds the substring "or" inside the word "for".

Is there an easy way to do this?

char[] terminationCharacters = new char[] { '\n', '\t', ' ', '\r' };

//get array with each word to be taken into consideration
string[] words= s.Split(terminationCharacters, StringSplitOptions.RemoveEmptyEntries);

int indexOfWordInArray = Array.IndexOf(words, wordToFind);
int indexOfWordInS = 0;
for (int i = 0; i <= indexOfWordInArray; i++)
{
    indexOfWordInS += words[i].Length;
}
return indexOfWordInS;

      

But this obviously may not work if there are multiple spaces between words. Is there any pre-designed way to do this seemingly simple thing, or should I just use it Regex

?

+3


source to share


2 answers


You can use regex:

var match = Regex.Match("Potato for you", @"\bfor\b");
if (match.Success)
{
    int index = match.Index;
    ...
}

      



\b

indicates a word boundary.

If you don't need an index, but just want to check if a word is in a string, you can use IsMatch

that returns a boolean, rather than Match

.

+11


source


If you are looking for an index, you can do a method like this. If you only want to bool

see if it's there, then the method is a little simpler. Chances are there might be a way to do it with Regex in an easier way, but these are not my strong points.

I'll set it up as an extension method to make it easier to use.



public static int FindFullWord(this string search, string word)
{
    if (search == word || search.StartsWith(word + " "))
    {
        return 0;
    }
    else if (search.EndsWith(" " + word))
    {
        return search.Length - word.Length;
    }
    else if (search.Contains(" " + word + " "))
    {
        return search.IndexOf(" " + word + " ") + 1;
    }
    else {
        return -1;
    }
}

      

+1


source







All Articles