Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c# how do I count the number of words in each index of a string array?

For example I've got a text file that I've put into an array and then I have split that array by the full stops (so each sentence is in its own index of the new array) using the following:

textSplitArray = textArray[j].Split('.');

How would I then count the number of words in each index of textSplitArray to determine which sentence has the most words? Is it possible to do this or would I have to do it another way?

I've tried searching everywhere but can't seem to find an answer

like image 887
Csharpener Avatar asked Jan 19 '26 01:01

Csharpener


1 Answers

If you want to know which sentence is the longest (i.e. contains maximum words) use

var result = textSplitArray.OrderByDescending(x => x.Split(' ').Length)
                           .FirstOrDefault();

And if you want to know number of words in that longest sentence, use

int Max = textSplitArray.Max(x => x.Split(' ').Length);

OR

int Max = result.Length;

Since every two words in a sentence can be separated by space, that's why i have split each sentence based on ' ' space.

like image 100
Nikhil Agrawal Avatar answered Jan 20 '26 17:01

Nikhil Agrawal