Click here to Skip to main content
15,905,427 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi! I need a function who searches a string and find the number of occurrences of a given char within this given string. Can you help ? thank you.

I have tried this code below and it just gives all the chars within the string .. and my teacher said it was too complicated and I need to simplified it. And maybe I should define a string and a char and use a if else statement .. and I can't think of something else .. so please any ideas will be welcomed.

Sorry if you don't understand it well enough English is my second language and I tried to express myself as clearly as I can.

What I have tried:

C#
namespace ConsoleApplication5
{
    class ex3
    {
        static void Main(string[] args)
        {
            string str = "aabb12cc";
            var count = CharacterCount.Count(str);
            foreach (var character in count)
            {
                Console.WriteLine("{0}-{1}", character.Key, character.Value);
            }
        }

    }
    class CharacterCount
    {
        public static SortedDictionary<char, int=""> Count(string stringToCount)
        {
            SortedDictionary<char, int=""> characterCount = new SortedDictionary<char, int="">();
            foreach (var character in stringToCount)
            {
                int counter = 0;
                characterCount.TryGetValue(character, out counter);
                characterCount[character] = counter + 1;
            }
            return characterCount;
        }
    }
}
Posted
Updated 27-Nov-16 8:26am
Comments
PIEBALDconsult 27-Nov-16 14:22pm    
Why not
characterCount[character]++
?

I would add
if ( !characterCount.ContainsKey(character) ) characterCount [ character ] = 0

And I never use var, which is needless here.

1 solution

First thing that could simplify your code is the fact that the string is an array of chars. For example try what happens with the following code
C#
string str = "aabb12cc";
Console.WriteLine(str[3]);

Having that said, you could have a single loop looping through all the characters and if the character is desired one, then increment the counter by one. A simple loop could be a for (C# Reference)[^] loop starting from 0 and ending at the end of the string.
 
Share this answer
 
Comments
Member 12873209 28-Nov-16 11:09am    
Thank you. I managed to find the solution. You were right i used a for.
Wendelius 28-Nov-16 11:13am    
You're most welcome :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900