Searching for words in a string
-
Is there a fast way of finding the number of times a word appears in a string? Eg. String: "How do I search if a words exist in a string" Target Word: "a" Result: 2
Does this meet your needs?
string str = "How do I search if a words exist in a string"; MatchCollection mc = Regex.Matches(str, " a "); Console.WriteLine(mc.Count.ToString());
or perhaps...string str = "How do I search if a words exist in a string"; int index = str.IndexOf(" a "); int numWords = 0; while(index != -1) { index = str.IndexOf(" a ", index + 1); numWords++; } Console.WriteLine(numWords.ToString());
-
Does this meet your needs?
string str = "How do I search if a words exist in a string"; MatchCollection mc = Regex.Matches(str, " a "); Console.WriteLine(mc.Count.ToString());
or perhaps...string str = "How do I search if a words exist in a string"; int index = str.IndexOf(" a "); int numWords = 0; while(index != -1) { index = str.IndexOf(" a ", index + 1); numWords++; } Console.WriteLine(numWords.ToString());
-
V|ktor wrote: string str = "How do I search if a words exist in a string"; MatchCollection mc = Regex.Matches(str, " a "); Console.WriteLine(mc.Count.ToString()); Thank You! This worked great for me. Here's a 5. ;)
Just a little addition: V|ktor's solution will find the word only if it's surrounded by spaces. If you use @"\ba\b" instead, then the RE will match 'a' at the beginning or the end of the string, too. If you haven't done yet I suggest you read through this excellent tutorial: The 30 Minute Regex Tutorial [^] Regards, mav
-
Just a little addition: V|ktor's solution will find the word only if it's surrounded by spaces. If you use @"\ba\b" instead, then the RE will match 'a' at the beginning or the end of the string, too. If you haven't done yet I suggest you read through this excellent tutorial: The 30 Minute Regex Tutorial [^] Regards, mav