user3601310
user3601310

Reputation: 873

Counting words in each sentence using C#

I need to create a program that shows a sentence with the most words in it.

string [] st = { "I like apples.", 
                 "I like red apples.", 
                 "I like red apples than green apples." 
};

foreach (string s in st)
{
    int NumberOfWords = s.Split(' ').Length;
}

The result should be displaying "I like red apples than green apples".

Upvotes: 0

Views: 2921

Answers (6)

This should work

var text = @"This is some random text for testing";
var counts = text
    .Where(c => char.IsLetter(c)) // Make sure it's only a letter
    .Select(c => char.ToUpper(c)) // uppercase it
    .GroupBy(c => c) // Group the letters
    .Select(g => new 
    {
        Character = g.Key, 
        Count = g.Count(),
    }) // Select into char and count to make accessing easier
    .OrderBy(x => x.Character); // Order alphabetically
    
foreach (var c in counts)
{
    Console.WriteLine($"Letter: {c.Character}\t Count: {c.Count}");
}

output

Upvotes: 0

Aminul
Aminul

Reputation: 1738

You can use Regex.Matches() to get the number of words just like the following example:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
    const string t1 = "To be or not to be, that is the question.";
    Console.WriteLine(WordCounting.CountWords1(t1));

    const string t2 = "Mary had a little lamb.";
    Console.WriteLine(WordCounting.CountWords1(t2));
    }
}

/// <summary>
/// Contains methods for counting words.
/// </summary>
public static class WordCounting
{
    /// <summary>
    /// Count words with Regex.
    /// </summary>
    public static int CountWords1(string s)
    {
        MatchCollection collection = Regex.Matches(s, @"[\S]+");
        return collection.Count;
    }

}

Upvotes: 0

mihai
mihai

Reputation: 4722

var result = st
    .OrderByDescending(s => s.Split(' ').Count())
    .First();

Upvotes: 2

Ammar
Ammar

Reputation: 152

Your code is quite good if you read its documented summary then you will see s.Split() will return the substringcontaining the specified character. But if it is empty then you will get the number of words. So you can use it as:

int NumberOfWords = s.Split().Length;

Please Share the result.

EDIT: Before your loop declare an integer

int largest = 0;

Then in your loop write the code as

int NumberOfWords = s.Split().Length;
if(NumberOfWords > largest)
{
   this.label1.Text = s;
   largest = NumberOfWords;
}

By this you will get the string with larges words in the Text of your Label

Upvotes: 1

Zachary Cutler
Zachary Cutler

Reputation: 91

Here's a quick one-liner using Linq:

return st.Select(s => s.Split(' ')).OrderByDescending(a => a.Length).First().Aggregate((s, next) => s + " " + next);

So essentially we take 4 seperate operations and using Linq turn them into one statement.

  1. Turn the string array into an enumeration of string arrays where each string is now an array of its own split on the space character.
  2. Order the array (of arrays) by the length of each array (number of words) in descending order (largest, or longest, first).
  3. Select the first array (the longest).
  4. Take the array (your original string broken into an array of words) and join it back together into a single string.

In a class this may look like:

public string LongestString(params string[] args)
{
        return args.Select(s => s.Split(' ')).OrderByDescending(a => a.Length).FirstOrDefault().Aggregate((s, next) => s + " " + next);
}

You'll want to make sure you include the Linq namespace by including a "using System.Linq;" at the top of your file (if it's not already there).

Upvotes: 1

Rahul
Rahul

Reputation: 77876

Probably, you have the sentences in different TextBox control in your Form. For you to know which sentence have more words in it; split the sentence by space and get a count of words and then you can compare. something like below.

int str1 = "I like apples".Split(' ').Length;
int str2 = "I like red apples".Split(' ').Length;
int str3 = "I like red apples than green apples".Split(' ').Length;

Here split() functions returns a string array and so you can get Length of it. Now you can compare them easily.

EDIT:

Below would be a full example code drawn over your posted code. Store the word count in a int[] array. Then sort the array. Obviously the last element in arr below would be the one having highest words.

    static void Main(string[] args)
    {
        int[] arr = new int[3];           
        string[] st = { "I like apples.", "I like red apples.", 
                             "I like red apples than green apples." };
        int counter = 0;
        foreach (string s in st)
        {
            int NumberOfWords = s.Split(' ').Length;
            arr[counter] = NumberOfWords;
            counter++;
        }

        Array.Sort(arr);

        Console.WriteLine(st[arr.Length - 1]);
    }

Upvotes: 3

Related Questions