Reputation: 1161
I have a long string of characters as input and I want to count the number of words in that string. How can I do it through regular expression?
Upvotes: 1
Views: 177
Reputation: 7403
you can count number of words in string using following code
str = "CSharp split test";
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
int Count = strArr.Length;
Upvotes: 1
Reputation: 726639
You can make an expression \w+
, and use regex to enumerate the matches, like this:
var s = "Quick brown fox jumps over lazy dog";
foreach (var t in new Regex("\\w+").Matches(s)) {
Console.WriteLine(t);
}
Upvotes: 2
Reputation: 66641
You can simple do that (if you do not care for count numbers, and single chars also as words)
int CountOfWords = StringOf.Split(new char[] { ' ', '\n' },
StringSplitOptions.RemoveEmptyEntries).Length;
Split it to an array, with out count the empty entries, and then get that length. You can define also what you think that is separate your words.
Upvotes: 2