如何在字符串中搜索单词(只是单词)?

How to search for word in a string (just the word)?

我想在字符串中搜索一个词。

但是,如果搜索的词在其他词中,我不想得到结果。 即

如果我使用IndexOf,它会在单词"for".

中找到子串"or"

有什么简单的方法可以做到这一点吗?

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;

但是如果单词之间有多个空格,这显然可能行不通。 有没有任何预先构建的方法来做这件看似简单的事情,或者我应该只使用 Regex?

如果你正在寻找索引,你可以制作这样的方法。如果你只想要一个 bool 不管它是否在那里,那么该方法会稍微简单一些。更有可能的是,有一种方法可以更轻松地使用 Regex 执行此操作,但它们不是我的强项。

我将其设置为扩展方法,以使其更易于使用。

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;
    }
}

您可以使用正则表达式:

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

\b表示分词。

如果你不需要索引而只是想检查字符串中是否有这个词,你可以使用IsMatch,其中returns是一个布尔值,而不是[=13] =].