user1509
user1509

Reputation: 1161

Regular expression for finding a word

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

Answers (3)

R.D.
R.D.

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

Sergey Kalinichenko
Sergey Kalinichenko

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

Aristos
Aristos

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

Related Questions