Mohammad.I
Mohammad.I

Reputation: 1

Separate words from a string in C#

So i'm working on a program for a university degree. First requirement was to show the number of times each letter of the alphabet appears in a string. Now to develop this program further i would like to show all the words that are in the string, in a list. Here is the current code that i have.

public void occurances()
{
   string sentence;

   Console.WriteLine("\n");
   Console.WriteLine("Please enter a random sentence and press enter");
   Console.WriteLine("\n");

   var occurances = new Dictionary<char, int>();
   var words = occurances;

   //a for each loop, and within it, the char variable is a assigned named "characters"
   //The value "characters" will represent all the characters in the sentence string.
   sentence = Console.ReadLine();

   foreach (char characters in sentence)
   {
      //if the sentence contains characters 
      if (occurances.ContainsKey(characters))
      //add 1 to the value of occurances 
      occurances[characters] = occurances[characters] + 1;

      //otherwise keep the occurnaces value as 1
      else
         occurances[characters] = 1;
   }

   foreach (var entry in occurances)
   {
      //write onto the screen in position 0 and 1, where 0 will contain the entry key
      // and 1 will contain the amount of times the entry has been entered
      Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
   }
   //Pause
   Console.ReadLine();
}

Upvotes: 0

Views: 269

Answers (2)

Transcendent
Transcendent

Reputation: 5745

I thinks the easiest way would be this:

 var WordList = YourString.Split(' ').toList(); // Making the list of words

 var CharArray = YourString.toCharArray(); // Counting letters 
 var q = from x in CharArray
         group x by x into g
         let count = g.Count()
         orderby count descending
         select new {Value = g.Key, Count = count};

Upvotes: 1

Shiva
Shiva

Reputation: 20935

For 1st Requirement:

var charGroups =  sentence.GroupBy(x => x).OrderByDescending(x => x.Count());

For 2nd Requirement:

How to: Count Occurrences of a Word in a String (LINQ)

Upvotes: 1

Related Questions