我想为一个字搜索一个字符串。如何搜索字符串中的单词(只是单词)?
但是,如果搜索到的单词在其他单词内,我不想得到结果。 也就是说
我想这回7号(字母f的指数):
findWord("Potato for you", "for")
,但我想这个返回-1(即未找到)
findWord("Potato for you", "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
?
这是否适用于''为你''或'“土豆为”'?只是好奇'\ b'的规则是什么。 – krillgar
@krillgar,是的。字符串的开始或结束也被认为是一个字边界。 –