计算字符串S中所有数字的出现数量

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

本文关键字:数字 字符串 计算      更新时间:2023-10-16

输出格式:string = 7714

0 0

1 1

2 0

3 0 .....

7 2,依此类推。在每个数字的旁边都出现了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 开始的人,因此我想最好使用诸如数组和循环之类的基本结构。

阵列counts保留数字的计数,每个数字一个;因此,数组的大小为10。请注意,字符串中的字符不是0..9的积分数字,而是(很可能(来自(很可能(ASCII代码的字符48..57。字符'0'的ASCII代码是积分值48,而不是积分值0。因此,要获得0..9的范围,必须从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

算法的功能。。。

#include <iostream>
#include <string>
#include <algorithm>
int main()
{
    // Get String from user
    std::string s; std::cin >> s;
    // This is what we want to search
    std::string digits("0123456789");
    // Do all the work in a one liner
    std::for_each(digits.begin(), digits.end(), [&s](const char c) { std::cout << c << ' ' << std::count(s.begin(), s.end(), c) << 'n'; });
    return 0;
}

创建一个计数器数组。

int counters[10]; //will store the counts of each instance.
                 //counters[0] will count the number of 0s, etc.

将每个输入字符转换为整数。

look up how to do this on the internet.

递增该计数器数组的索引。

counters[the_converted_character_to_integer]++;