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?

Recommended Answers

All 5 Replies

The simpliest way would be to spit the string by white spaces into string array, and count the words (by Length property):

string text = "you long string";
string[] splitted = text.Split(' ');
int wordsCount = splitted.Length;

Or even better (shorter), by using Linq:

int a = text.Split(' ').Select(s => s.Length).Count();
commented: Now, how will I display the first 50 words, then next 50 words and so on? +0

Now, how will I display the first 50 words, then next 50 words and so on?

I would like you to continue using Linq, which is really some piece of work from MS.

To get 1st 50 words:

string text = "you long string";
var result_1st50 = text.Split(' ').Select(s=>s.Lenght).Take(50).ToList();

To get next 50 (and skip 1st 50):

var result_1st50 = text.Split(' ').Select(s=>s.Lenght).Skip(50).Take(50).ToList();

As you can see, Skip will skip the number of words, while Take will get the number of words. For example if you wanna get words from 350 to 400, you only change:
//.Skip(350).Take(50).ToList();

ToList() is the annonimus method, that already create a new list of strings, so no need of any further loop.

var result_1st50 = text.Split(' ').Select(s=>s.Lenght).Take(50).ToList()

This will return a list of the lengths of the words, not a list of the words. Remove the Select statement
List<String> result_1st50 = text.Split(' ').Take(50).ToList();

Ups, sorry, you are right. I copied the previous code, and I guess forgot to duble check it.
My intentions were good....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.