Well i am doing a very simple program that is to calculate the number of occurrance of a character in a string

Hello World

The character H appears 1 times
The character E appaers 2 times
The character L appears 3 times
The character L appears 3 times
The character o appears 2 times
The character W appears 1 times
The character O appears 2 times
The character R appears 1 times
The character L appears 3 times


Here the problem is that for same character L it is printing output line 3 times .......thats not what i want...........tell me a professional approach........I know i can store them in some different array but i want something else

The character L appears 3 times
The character L appears 3 times
The character L appears 3 times

So its your turn to Help me out...........I am doing this one in Java Script but i am looking for login to implemnet not code

Thanks

Sumit Taneja

1. Don't print a character if it's already printed. This you figure out using an extra array/vectory/...
2. While counting use a map of character vs count. Map will ensure there is only one entry for a given key.

hi, how about this code.
I just tried avoiding array and I want to see if I can do it without array.

String s = "Hello World I am happy with you guys";
String n = "";    //used to save non repeated characters
int length = s.length();
while(length != 0)
{
    int count = 0;
    String ch = s.substring(0,1);    //take first character and check it
            for(int i = 0 ; i<length;i++)//this loop will increment number of Occurance and then take repeated characters away from the string so that not to print them again.
            {
                String t = s.substring(i,i+1);
                if(!(t.equalsIgnoreCase(ch)))//put char not equal in new String
                {
                    n = n+s.substring(i,i+1);
                }
                else// if equal just increment count
                {
                    count++;
                }
            }
            System.out.println("The character"+ch+" appears"+count);    
            s = n;// set the string taken from the loop with repeated char eliminated to the original one.
            length = s.length();// DON'T forget length
            n = "";//clean n to start again with empty one and commulate again.

for example, the first iteration you will take "H" and count number of occurance and eliminate that occurance from string. n will be equal to"ello World I am appy wit you guys". You can see "H" is cleaned. Now , Do the same thing with this new n (that is why at end you see s = n)

At the end you can see that I used 2 loops, so my code will have somehow high complexity if String is too long

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.