Want more features on Pastebin? Sign Up, it's FREE!
Guest

Splitting words.

By: a guest on Nov 9th, 2012  |  syntax: C#  |  size: 1.42 KB  |  views: 29  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10.  
  11. namespace WindowsFormsApplication4
  12. {
  13.   public partial class Form1 : Form
  14.   {
  15.     public Form1()
  16.     {
  17.       InitializeComponent();
  18.     }
  19.  
  20.     public void CountWords(string input)
  21.     {
  22.       //A place to store all the words and the count
  23.       var result = new Dictionary<string, int>();
  24.  
  25.       foreach (string word in input.Split(' '))
  26.       {
  27.         //variable I'm not going to use...
  28.         int count;
  29.         //Check if word is already exists. I added .ToLower() to make it case insensitive.
  30.         if (result.TryGetValue(word, out count))
  31.         {
  32.           //It already exists, so I increase the count by 1
  33.           result[word]++;
  34.         }
  35.         else
  36.         {
  37.           //It is new, so I add the word, with a count of 1.
  38.           result.Add(word, 1);
  39.         }
  40.       }
  41.  
  42.       //Order results
  43.       var OrderedResult = result.OrderBy(l => l.Key);
  44.  
  45.       //Print results
  46.       foreach (KeyValuePair<string, int> item in OrderedResult)
  47.       {
  48.         Console.WriteLine("Word: {0}, count: {1}", item.Key, item.Value);
  49.       }
  50.  
  51.     }
  52.  
  53.     private void button1_Click(object sender, EventArgs e)
  54.     {
  55.       CountWords("My face is not much like your face");
  56.     }
  57.   }
  58. }
clone this paste RAW Paste Data