计算字符串S中所有数字的出现数量
Count the number of occurrences of all the digits in the string S.?
输出格式: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]++;
相关文章:
- 生成随机长度的数字字符串
- 如何在c ++中将大数字字符串转换为整数?
- 将非数字字符串存储为二进制整数
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何在C++中将数字字符串拆分为数组
- 总结数字字符串输入的最佳方法
- 如何将输入的数字字符串转换为 int 数组
- 如何获得两个数字字符串的总和-C
- 使用 C++ 替换 txt 文件中的文本数字字符串
- 如何有效地将数字字符串值分配给整数
- String Stream in C++ 解析单词和数字字符串
- c++将大型数字字符串映射到数字字符串范围
- 获取用数字字符串表示的树中的所有直接父级/子级
- 如何从 char 数组中提取数字字符串成员
- 比较两个字母数字字符串
- 有没有一种方法可以设置浮点变量=某个数字*字符串中的变量
- 使用矢量对字母数字字符串进行排序
- 正在分析未知类型的数字字符串
- 如何在c++中从一个科学数字字符串中修剪后面的零
- 无法将字符串数组中的数字字符串转换为浮点值