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?

6 Years
Discussion Span
Last Post by Mitja Bonca

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();
Votes + Comments
Now, how will I display the first 50 words, then next 50 words and so on?

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:

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....

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.