Link to home
Start Free TrialLog in
Avatar of klay8
klay8

asked on

c# String operations

hi
i would like to count the number of words that i have typed:
For example:
The cat in the hat  5 words
The cat, in the hat  5 words
The cat , in the hat  5 words
The cat
 
in the hat  5 words

Note: Quote characters have been used to denote the start and end of the string.  

 a word is defined as a continuous string of the character ranges a-z, A-Z or 0-9 separated by one or more other characters e.g. a012jtU is one word, a0G1#2jtU is two words because the # is a separator.

tanks
ASKER CERTIFIED SOLUTION
Avatar of Anurag Thakur
Anurag Thakur
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of klay8
klay8

ASKER

what about this a0G1#2jtU??
a0G1#2jtU is two words,
# as a separator
\S+ defines the separator between the words
you can add more separators too
Avatar of klay8

ASKER

so what will be the pattern?
Avatar of klay8

ASKER

actually not only # is a separator, all non alphanumerics are separators in this example
try

[a-zA-Z0-9]+
string inp = "The cat, in t#he hat";
Regex regex = new Regex("[a-zA-Z0-9]+");
 
MatchCollection matches = regex.Matches(inp);
 
int count = matches.Count;

Open in new window