【问题标题】:How to search for word in a string (just the word)?如何在字符串中搜索单词(只是单词)?
【发布时间】:2015-04-26 00:42:57
【问题描述】:

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

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

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

    findWord("土豆给你", "for")
  • 但我希望它返回 -1(即未找到)

    findWord("给你的土豆", "or")

如果我使用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

【问题讨论】:

    标签: c# string word


    【解决方案1】:

    你可以使用正则表达式:

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

    \b 表示单词边界。

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

    【讨论】:

    • 这对"for you""Potato for" 有效吗?只是好奇\b 的规则是什么。
    • @krillgar,是的。字符串的开头或结尾也被视为单词边界。
    【解决方案2】:

    如果你正在寻找索引,你可以做一个这样的方法。如果您只想要一个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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-27
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      相关资源
      最近更新 更多