locked
How to count the number of duplicate chars in a string RRS feed

  • Question

  • I need to count the number of duplicate chars in  a string:

    aabbcc : 
    -a - 2
    -b - 2
    -c - 2

    or : aaab -  - 2; b - 1;

    Any hint please, I'm stuck. Thanks

    I try this:

    foreach(char c in p1)
                {
                    int index = text.IndexOf(c);
    
                    if (c == text[index])
                    {
                       
                        count++;
                    }
                    if(c != text[index])
                    {
                        countsinglenumbers++;
                    }
                    a++;
                }

     
    Sunday, October 4, 2020 7:24 PM

Answers

  • you can use Enumerable.GroupBy:
    using System.Linq;
    
    string test = "aabbcc";
    var grouped = test.GroupBy(c => c);
    foreach (var group in grouped)
    {
        Console.WriteLine($"{group.Key}: {group.Count()}");
    }

    • Marked as answer by keeponfalling Sunday, October 4, 2020 8:01 PM
    Sunday, October 4, 2020 7:51 PM

All replies


  • or : aaab -  - 3; b - 1;



     

    Sunday, October 4, 2020 7:26 PM
  • you can use Enumerable.GroupBy:
    using System.Linq;
    
    string test = "aabbcc";
    var grouped = test.GroupBy(c => c);
    foreach (var group in grouped)
    {
        Console.WriteLine($"{group.Key}: {group.Count()}");
    }

    • Marked as answer by keeponfalling Sunday, October 4, 2020 8:01 PM
    Sunday, October 4, 2020 7:51 PM
  • It's a course assigment and I can't use LINQ, I need a base algoritm
    Sunday, October 4, 2020 8:02 PM
  • when this is a course asignement you should write the algorithm for yourself.
    Are you at least allowed to use a dictionary?
    then you can use a  Dictionary<char, int>
    iterate over the string, when dictionary does not yet contain a value for char: add 1,
    else increment the value
    Monday, October 5, 2020 5:02 AM