-4

Edit :I elaborated My Question More ..solutions are here for one fix duplicate word .. I was asked about every duplicate word

I am a Newbie ...Might be not a Good question . ......

this is string

string str = "this this is is a a string"

in Interview ,i was asked to store the count of every duplicate keyword in generic Dictionary and then display them in Order

for example No of occurance of "is" keyword is 2

similar Links
: Find the most occurrence of a character in string C#? this is about finding character

Finding occurrences of words in text which are in a list words this is in python

Remove occurrences of duplicate words in a string this in javaScript

How to use the string.match method to find multiple occurrences of the same word in a string? Not relevant

..please Suggest

Community
  • 1
  • 1
user3487944
  • 267
  • 4
  • 9
  • 22
  • 1
    A dictionary holds a key and a value. You will need to split the string, and save the count of each word in your dictionary. If you run into specific problems, post your code with what you are running into. – Kevin Anderson Apr 25 '14 at 12:15
  • Your question is fine. You just haven't shown any effort to figure it out. You're basically asking SO to write code for you. – Jon B Apr 25 '14 at 12:18
  • I simplified my question ...... – user3487944 Apr 25 '14 at 14:10

3 Answers3

13

Pretty simple with LINQ:

string str = "this is is a string";
string[] words = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

(You could alternatively use Regex.Split(str, @"\W+") like @markieo did in his answer. The difference is that it will also detect words surrounded by quotes and other punctuation marks. Thanks for @JonB for pointing this aspect out in comments.)

Dictionary<string, int> statistics = words
    .GroupBy(word => word)
    .ToDictionary(
        kvp => kvp.Key, // the word itself is the key
        kvp => kvp.Count()); // number of occurences is the value
int isCount = statistics["is"]; // returns 2

EDIT:

I'm posting code addressing your enhanced requirements. But for the future, just post another question instead of modifying one that's been answered!

// retrieving all duplicate words
string[] duplicates = statistics
    .Where(kvp => kvp.Value > 1)
    .Select(kvp => kvp.Key)
    .ToArray();

// counting all duplicates and formatting it into a list in the desired output format
string output = String.Join(
    "\n", 
    statistics
        .Where(kvp => kvp.Value > 1)
        .Select(kvp => 
            String.Format(
                "count(\"{0}\") = {1}", 
                kvp.Key, 
                kvp.Value))
        .ToArray() // this line is only needed on older versions of .NET framework
);
Konrad Morawski
  • 8,307
  • 7
  • 53
  • 91
1

Try the above:

    string str = "this this is is a a string";
    private int count(string key)
    {
        string[] ar = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
        Dictionary<int, string> d = new Dictionary<int, string>();

        for (int i = 0; i < ar.Length; i++)
            d.Add(i, ar[i]);
       return d.Where(x => x.Value == key).ToList().Count;
    }

The function call :

count(str, "is");
kostas ch.
  • 1,960
  • 1
  • 17
  • 30
  • what about every duplicate word .. do i need to hardcord each of them?? .I edited my question – user3487944 Apr 25 '14 at 12:45
  • @user3487944 As you have changed your question i will change my answer too at the moment. This post was for the original question. – kostas ch. Apr 25 '14 at 12:49
  • So you mean i have to pass duplicate word hardcoded-ly to count its occurance .. – user3487944 Apr 25 '14 at 12:56
  • @user3487944 Exactly as you asked in your question "count("this") =2 count("is") =2 count("a") =2". – kostas ch. Apr 25 '14 at 12:58
  • NO .No ..this is just a sample ..what about there are more duplicate words .. – user3487944 Apr 25 '14 at 13:06
  • @user3487944 Do a simple loop for the duplicate words. THIS answers what you have asked. Ask other question to get other answer... – kostas ch. Apr 25 '14 at 13:09
  • kanord suggestion to use ".GroupBy(word => word).ToDictionary()"..helped – user3487944 Apr 25 '14 at 13:24
  • @user3487944 This is a forum that people help other people. Please respect the time that people spend to help you!!! This comment does not show that you respect my time that i have spend for you. – kostas ch. Apr 25 '14 at 13:28
  • thanks for giving me solution ..i didnt mean to be rude... i was just discussing that I have also tried to do ways for some fix words in interview but interviewer didnt accept that ..I couldnt able to explain my question initially.. – user3487944 Apr 25 '14 at 13:48
  • @user3487944 Better be your self in the interview and not someone else. If you do not know something just say "i don't know" or try to find a solution by yourself. – kostas ch. Apr 25 '14 at 13:53
  • thanks for giving your valuable time ..for every question I cant say "i dont know" ..interview observe the logical and programming efforts – user3487944 Apr 25 '14 at 13:56
  • @user3487944 i did not say that. Try to find solution by yourself, with your knowledge, with your experience because what will happen if you get the job and you must be at customer's place and write code? I telling these because i have my own business and i recruiting people. I don't want to get someone that said me knows 5 things and in reality knows 1! – kostas ch. Apr 25 '14 at 14:00
  • yes , first we need to find solution on our own .. and should have discussion after doing efforts – user3487944 Apr 25 '14 at 14:13
0

You can use this code to get an array of all the words in a string.

static string[] SplitWords(string s)
{
     return Regex.Split(s, @"\W+");
}

And then you can use a foreach loop to count all the times the word comes in the array. Like this:

int count = 0;
foreach(string s in SplitWords("This is is a string"){
    if(s == "is"){
    count++;
    }
}

int count is the times the word comes in the string.

Source: http://www.dotnetperls.com/split

markieo
  • 484
  • 3
  • 14