我想在字符串中搜索一个单词。
但是,如果搜索到的单词在另一个单词内,我不想得到结果。
那是
我希望它返回数字7(字母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 will find the substring "or" inside the word "for".
Is there any simple 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;
但是,如果单词之间有多个空格,这显然可能行不通。
是否有任何预先构建的方式可以执行此看似简单的操作,还是应该只使用
Regex
? 最佳答案
您可以使用正则表达式:
var match = Regex.Match("Potato for you", @"\bfor\b");
if (match.Success)
{
int index = match.Index;
...
}
\b
表示单词边界。如果不需要索引,而只想检查单词是否在字符串中,则可以使用
IsMatch
,它返回一个布尔值,而不是Match
。