c++ - 计算字符串 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++ 开始的人,所以我认为最好使用数组和循环等基本结构。
该数组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
推荐阅读
- php - 使用 eloquent laravel 优化查询
- javascript - 如何将高阶组件连接到 Redux 商店?
- vue.js - 为什么我有 2 种不同类型的 Vue?
- php - 为什么我的 IDE 将此匿名 PHP 函数标记为语法错误?
- python - 自动化无聊的东西第4章人物图片网格
- java - 尝试给出很长的字符串时,SubString 给出 OutOfMemory 异常
- r - 在 R 中:如何循环 data_A 中的名称以根据 data_A 中的 ColumnNum 从 data_B 中选择列?
- spring - 如何使用spring boot根据参数值保护具有不同身份验证的单页应用程序?
- kubernetes - 什么是 Istio 外部服务?
- c# - 连接两个表与三个 ON