Click here to Skip to main content
15,881,516 members
Please Sign up or sign in to vote.
1.57/5 (3 votes)
How to write a c# program in which it takes input as "Twinkle, Twinkle, Little Star" .
It will give output as
Twinkle - 2,
Little - 1,
Star - 1

means word with its count in a sentence .

Thanks.
Posted

You can try this:
C#
string sentence = "Twinkle, Twinkle, Little Star";
string[] words = sentence.Split(new char[] { ' ', ',', '.', '!', ':', '?', ';' }, StringSplitOptions.RemoveEmptyEntries); // this splits the string into the words
var groups = words.GroupBy(x => x); // this groups the words
foreach (var group in groups)
{
    Console.WriteLine("{0} - {1}", group.Key, group.Count());
}

How this works: after splitting the sentence into words, you group the words. Then you iterate over all groups and you print the key (the word) and the count of words in the group.
 
Share this answer
 
Comments
Thanks7872 21-Jan-14 13:32pm    
+5 !
Thomas Daniels 21-Jan-14 13:34pm    
Thank you!
Rahul VB 21-Jan-14 13:45pm    
very nice sir,
+5
Thomas Daniels 21-Jan-14 13:45pm    
Thank you!
BillWoodruff 21-Jan-14 20:27pm    
+5 This is the way it should be done.
Refer the technique at C# String Occurrence Count[^]
 
Share this answer
 
Hello,

try out this :


C#
static void Main(string[] args)
       {

           //string sentence = "twinkle, twinkle, little star";
           do
           {
               Console.WriteLine("Enter a sentence");
               string sentence = Console.ReadLine();

               string[] data = sentence.Split(',', ' ');
               int count = 0;
               int original_count = data.Length;
               for (int i = 0; i < data.Length; i++)
               {
                   if (data[i] == "")
                       count++;
                   Console.WriteLine(data[i]);
               }

               original_count = original_count - count;
               Console.WriteLine(original_count.ToString());
               Console.WriteLine("Press enter to continue.......");
               Console.ReadLine();
               Console.Clear();

           } while (true);

       }



- This is a console application, when you run it when prompted simply enter the sentence whose count you want to find out. Also you need to add as many possible combinations of delimiters as you can think a person can put in his sentence.
- I have added a few.
- Try out different combinations and please do tell me.

Thanks,
Rahul
 
Share this answer
 
v2
Homework... Homework... Homework...

MSDN[^] is here to help..

Small tip : get the words by removing spaces and increment the counter.!!
 
Share this answer
 
Comments
Rahul VB 21-Jan-14 13:35pm    
absolutely, correct. I have posted a solution. It may have bugs.
Thanks,
-Rahul

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900