编写一个函数,统计一个字符串中 0~9 出现的次数。函数原型如下:
void count( string &s, int counts[ ], int size ) ;
其中,s 为字符串,数组元素 counts 表示 0~9 出现的次数,size 为 counts 数组大小
#include <iostream>
using namespace std;
void count( string &s, int counts[ ], int size ) {
int value;
for (int i = 0; i < s.length(); i++) {
value = s[i] - '0';
if (value >= 0 && value <= 9 && value < size) {
counts[value]++;
}
}
return ;
}
int main()
{
#define C_SIZE 3
string s = "1231456adb";
int c[C_SIZE] = {0};
count(s, c, C_SIZE);
for(int i = 0; i < C_SIZE; i++) {
cout << c[i] << endl;
}
return 0;
}
void count( string &s, int counts[ ], int size ){
for( int i = 0; i < s.length(); i++ )
if( '0' <= s[i] && s[i] <= '9' )
counts[s[i] - '0']++;
}