Counting number of repeating characters in a string?

If I got a string like "bookkeeper", how can I count the number of following characters that are repeating?
I would get an output like this: "1b2o2k2e1p1e1r"

Here's what I tried so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
       String s= "bookkeeper";

            for (int i=0 ; i < s.length(); i++)
            {
                int sum = 0;
            	 for (int j = 0; j < s.length(); j++)
            	 	 {
				  if (s.at(i) == s.at(j))
					  sum++;
            	 	 }

            	 cout << sum<< s.at(i) ;
            }


But the output gives me "1b2o2o2k2k3e3e1p3e1r" . Any help please?
Last edited on
Your not ignoring characters that you already checked.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
      bool notYetRead(std::string aR, char c){
            bool inStr = false;
            for(int i = 0;aR[i] != '\0';i++){
                 if(c == aR[i]){
                      inStr = true;
                 }
            }
            return !inStr;
      }



       string aR = "";
       String s= "bookkeeper";

            for (int i=0 ; i < s.length(); i++)
            {
                int sum = 0;
                aR += s[i];
            	 for (int j = 0; j < s.length(); j++)
            	 	 {
				  if (s.at(i) == s.at(j) && notYetRead(aR,s[i]))
					  sum++;
            	 	 }
                 if( notYetRead(s[i]) )
            	         cout << sum<< s.at(i) ;
            }


That should work. Still check it yourself though.
Last edited on
I corrected the error on your code in line 25 and changed it to
1
2
                       if( notYetRead(aR,s[i]))
                  	         cout << sum<< s.at(i) 

But when I run it , it prints nothing , I think it just hangs in a loop.
Last edited on
If I understand correctly, this is an O(n) problem that you're both overthinking. The problem is to print subsequences of identical characters as the length of the sequence followed by the character.

So why do both your solutions use nested for loops? All you need is a variable to store the "current" character and how many of that character you've found in a sequence. Example solution (which I might redact later if I feel regret about posting it):

1
2
3
4
5
6
7
8
9
10
11
char current = input.front();
int count = 0;
for(char c: input) {
    if(c == current) ++count;
    else {
        std::cout << count << current;
        current = c;
        count = 1;
    }
}
std::cout << count << current << std::endl;


-Albatross

EDIT: Grammatical typo.
Last edited on
Yes , that helped fix the problem. Thanks very much Albatross.
Topic archived. No new replies allowed.