首页 > 解决方案 > 计算字符串 S 中所有数字出现的次数。?

问题描述

输出格式:字符串 = 7714

0 0

1 1

2 0

3 0 ...

7 2 以此类推,直到第 9 位。注意:每个数字出现值后都会有新的一行。在每个数字旁边出现相同的出现,即 15 或 20 或 25。

#include <iostream>

using namespace std;

int main()

{

    string s;
    cin>>s;
    int i,j;
    int c=0;
    int a;
    int l=s.length();
    for(i=0;i<l;i++)
    {
        cin>>s[i];
    }
    for(i=0;i<l;i++)
    {
        for(j=0;j<=9;j++)
        {
        if(s[j]==1 || s[j]==2 || s[j]==3 || s[j]==4 || s[j]==5 || s[j]==6 || s[j]==7 || s[j]==8 || s[j]==9 || s[j]==0)
        {
            c++;
        }
        }
    }
    for(i=0;i<=9;i++)
    {
        cout<<i<<" "<<c<<endl;
    }

}

标签: c++string

解决方案


由于一天后到目前为止所有的评论和答案显然对您没有帮助,请参阅以下简单的解决方案。

该练习针对的是从 C++ 开始的人,所以我认为最好使用数组和循环等基本结构。

该数组counts保存数字的计数,每个可能的数字一个;所以数组的大小是 10。请注意,字符串中的字符不是0..9的整数,而是(很可能)48..57 的 ASCII 码中的字符。字符 '0' 的 ASCII 码是整数值 48,而不是整数值 0。因此,要获得 0..9 的范围,必须减去 48(或 '0',与整数 48 相同)相应的字符。希望能帮助到你。

#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;
    }
}

输出:

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

推荐阅读