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

时间:2015-04-26 00:42:58

标签: c# string word

我想在字符串中搜索单词。

但是,如果搜索的单词在其他单词内,我不想得到结果。 那是

  • 我希望这返回数字7(字母f的索引):

    findWord("Potato for you", "for")
  • 但我想让它返回-1(即未找到)

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

如果我使用IndexOf,它会在单词“for”中找到子字符串“或”。

有没有简单的方法可以做到这一点?

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

2 个答案:

答案 0 :(得分:11)

您可以使用正则表达式:

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

\b表示单词边界。

如果您不需要索引,但只是想检查单词是否在字符串中,则可以使用IsMatch,它返回布尔值,而不是Match。< / p>

答案 1 :(得分:1)

如果您正在寻找索引,可以制作这样的方法。如果你只想要一个bool,那么这个方法会更简单一些。更有可能的是,有一种方法可以更容易地使用正则表达式,但它们不是我的强项。

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

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;
    }
}
相关问题