Answered by:
String Contains

Question
-
Answers
-
Use Regex with the \b anchor:
const string s1 = "i meant"; const string s2 = "she is so mean, sometimes"; const string pattern = @"\bmean\b"; Console.WriteLine("ismatch: {0}: {1}", s1, Regex.IsMatch(s1, pattern)); Console.WriteLine("ismatch: {0}: {1}", s2, Regex.IsMatch(s2, pattern));
'\b' denotes a "word boundary". Tt will also match " i mean."
or a the word "mean" itself - but not "mean" inclosed in another
word/token, ffr: Regular Expression Language Elements
Chris
All replies
-
-
Thanks! I have another question, how can I only make the code execute if the string from the array is a word by itself.
e.g. word = "I meant"
_words = "mean"
and it wont execute? I'm having a bit of trouble with my current code cause the two spaces at the front and the end are missing things up.
-
So, if your words array contains "mean" you want to be able to find it in "I meant", is that correct?
If so, then you should probably use String.IndexOf which will give you the first occurrence of that word in the string, you could then use the overloaded IndexOf method which allows you to specify a starting index.
Here's an example from MSDN...
http://msdn.microsoft.com/en-us/library/ms131434.aspx
K
-
No, I don't want it to find inside "I meant". I want exactly the opposite but I want it to find the word alone, currently I'm using two spacing at the start and the end of each word but if the player simply writes "badword", "badword " or " badword" it wont find anything.
-
http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx
This will allow you to find if a word you seek is whithin another string.
Regards
-
Use Regex with the \b anchor:
const string s1 = "i meant"; const string s2 = "she is so mean, sometimes"; const string pattern = @"\bmean\b"; Console.WriteLine("ismatch: {0}: {1}", s1, Regex.IsMatch(s1, pattern)); Console.WriteLine("ismatch: {0}: {1}", s2, Regex.IsMatch(s2, pattern));
'\b' denotes a "word boundary". Tt will also match " i mean."
or a the word "mean" itself - but not "mean" inclosed in another
word/token, ffr: Regular Expression Language Elements
Chris
-