c# - How to search for word in a string (just the word)? -
i want search string word.
however, don't want result if word searched inside other word. is
i want return number 7 (index of letter f):
findword("potato you", "for")
but want return -1 (i.e., not found)
findword("potato you", "or")
if use indexof
, find substring "or" inside word "for".
is there simple way this?
char[] terminationcharacters = new char[] { '\n', '\t', ' ', '\r' }; //get array each word taken consideration string[] words= s.split(terminationcharacters, stringsplitoptions.removeemptyentries); int indexofwordinarray = array.indexof(words, wordtofind); int indexofwordins = 0; (int = 0; <= indexofwordinarray; i++) { indexofwordins += words[i].length; } return indexofwordins;
but may not work if there multiple spaces between words. there pre-built way apparently simple thing, or should use regex
?
you can use regular expression:
var match = regex.match("potato you", @"\bfor\b"); if (match.success) { int index = match.index; ... }
\b
indicates word boundary.
if don't need index want check if word in string, can use ismatch
, returns boolean, instead of match
.
Comments
Post a Comment