[Solved] Count the number of occurrences of all the digits in the string S.?


Since after one day all the comments and answers so far obviously could not help you, see the following simple solution.

The exercise targets people starting with C++, so I suppose it is better to use basic constructs like arrays and loops.

The array counts holds the counts of the digits, one for each possible digit; so the size of the array is 10. Note that the characters in the string are not integral digits from 0..9, but characters in (very likely) ASCII code from 48..57. The ASCII-code of character ‘0’ is integral value 48, not integral value 0. So to get a range from 0..9, one has to substract 48 (or ‘0’, which is the same as integral 48) from the respective character.
Hope it helps.

#include <iostream>
#include <string>

int main() {

    std::string s = "7714";
    int counts[10] =  { 0 };  // init all the counters with 0
    for (int i=0; i<s.length();i++) {  // iterate over the characters in s
        char c = s[i];
        if (isdigit(c)) {
            int index = c - '0'; // c is from '0' to '9' (i.e. ASCII codes 48..57); need it from 0..9; char('0') stands for int(49).
            counts[index]++;  // increment the counter representing the respective digit
        } else {
            std::cout << "invalid character (not a digit) in s" << std::endl;
        }
    }
    for (int i=0; i<9; i++) {
        std::cout << i << ": " << counts[i] << std::endl;
    }
}

Output:

0: 0
1: 1
2: 0
3: 0
4: 1
5: 0
6: 0
7: 2
8: 0

2

solved Count the number of occurrences of all the digits in the string S.?