• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 443
  • Last Modified:

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
0
klay8
Asked:
klay8
  • 3
  • 2
1 Solution
 
Anurag ThakurTechnical ManagerCommented:
string pattern = @"\b(\S+)\b";
int wordCount = Regex.Matches ("The cat , in the hat", pattern, RegexOptions.None).Count;

wordcount has 5 in it
0
 
klay8Author Commented:
what about this a0G1#2jtU??
a0G1#2jtU is two words,
# as a separator
0
 
Anurag ThakurTechnical ManagerCommented:
\S+ defines the separator between the words
you can add more separators too
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
klay8Author Commented:
so what will be the pattern?
0
 
klay8Author Commented:
actually not only # is a separator, all non alphanumerics are separators in this example
0
 
Tony McCreathTechnical SEO ConsultantCommented:
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

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now