Employers - Post Free Jobs
Forum guidelines
AuthorQuestion
interview question
Posted on: 20 Dec 2012
had interivew want the answer for

"by the people we the people"
write the c# program to count
by=1
the=2
people=2
we=1
 
can anybody help to find the ans


AuthorReply
Vulpes
  • 2
  • 0
accepted
Re: interview question
Posted on: 20 Dec 2012   Accepted Answer
This should do it:

using System;
using System.Collections.Generic;

class Program
{
   static void Main()
   {
     string s = "by the people we the people";
     string[] words = s.Split(' ');
     Dictionary<string, int> dict = new Dictionary<string, int>();
     foreach(string word in words)
     {
        if (dict.ContainsKey(word))
        {
           dict[word]++;
        }
        else
        {
           dict.Add(word, 1);
        }
     }

     foreach(string key in dict.Keys)
     {
        Console.WriteLine("{0}={1}", key, dict[key]); 
     }

     Console.ReadKey();     
   }
}


Re: interview question
Posted on: 21 Dec 2012  
hi vulpes you got correct answer but please can commentout what did you did in for each loop. as i have said i am new to .net it will help me out thanks thanks have a nice day
Re: interview question
Posted on: 21 Dec 2012  
Why don't you debug the application and have a look by performing step by step operation
Re: interview question
Posted on: 21 Dec 2012  
Here's a fully commented version of the program:

using System;
using System.Collections.Generic; // needed for Dictionary class

class Program
{
   static void Main()
   {
     string s = "by the people we the people";
     string[] words = s.Split(' '); // split 's' into words using the spaces as the delimiter
     // create a new Dictionary whose key is a string and value an integer
     Dictionary<string, int> dict = new Dictionary<string, int>(); 
     foreach(string word in words) // iterate through the words
     {
        if (dict.ContainsKey(word)) // if the word is already in the Dictionary
        {
           dict[word]++; // increase the value (i.e. number of occurrences) by 1
        }
        else // if the word is not in the Dictionary
        {
           dict.Add(word, 1); // add it with a value of 1
        }
     }

     foreach(string key in dict.Keys) // iterate through the Dictionary's keys
     {
        Console.WriteLine("{0}={1}", key, dict[key]); // print out the key/value pairs 
     }

     Console.ReadKey(); // keep console open till a key is pressed   
   }
}


SPONSORED BY

Offshore Software and Database Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.