检查字符串中每个字符出现的问题
Problems in checking for occurence of each character in a string
我正在尝试制作一个程序,该程序计算字符串中每个每个字符的情况,例如:
Enter string: hello world
输出为
h: 1
e: 1
l: 3
o: 2
...等等
,但我的输出似乎遍布全部,例如:
Enter string: nice on ice
n: 2
i: 2
c: 1
e: 1 //there should be 2 e's
o: 1
有时喜欢:
Enter string: potato
p: 1
o: 2
t: 2
a: 1
: 1
这是我的代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main() {
char l, str[30], cpy[30];
int i, j, occ;
i = j = 0;
occ = 0;
cout << "Enter string: ";
fgets(str, 10, stdin);
strcpy(cpy, str); // copy the string as I am about to modify it
// Checks for occurences of each character.
// Every character found is changed to a ' ' so that it isn't counted again
while (str[i] != ' ') {
occ = 0;
if (str[i] != ' ') {
l = str[i];
for (j = 0; str[j] != ' '; j++) {
if (str[j] == cpy[i] && str[j] != ' ') {
occ++;
str[j] = ' ';
}
}
cout << l << ": " << occ <<endl;
}
i++;
}
cout << "n";
fputs(str, stdout); // just to check if all characters were converted to ' '
cout << "n";
return 0;
}
您实际上不需要制作副本,并且您的内部循环正在做太多工作,迭代已经无效的字符。另外,您似乎对副本或原始内容是由i
或j
索引的困惑。
int main()
{
char str[30];
int i, j, occ;
cout << "Enter string: ";
fgets(str, 10, stdin);
// Checks for occurences of each character.
// Every character found is changed to a ' ' so that it isn't counted again
for(i = 0; str[i] != ' '; i++)
{
if (str[i] != ' ')
{
// Output the current character before it is invalidated.
cout << str[i] << ": ";
// Start at the current character so that it is counted
// at least once.
occ = 0;
for (j = i; str[j] != ' '; j++)
{
// No need to test for ' ', because str[i] is not
// a ' ', so equality is sufficient.
if (str[j] == str[i])
{
occ++;
// Invalidate each counted character.
str[j] = ' ';
}
}
cout << occ << endl;
}
}
// just to check if all characters were converted to ' '
cout << endl << str << endl;
return 0;
}
对于您的作业解决方案,请记住,英语字母中有26个字母,将每个字母转换为索引很容易将索引转换为数组(ASCII编码是<它是>极度简单)。它是>
武装此信息,请考虑具有26个整数的数组,其中数组中的每个元素都是您读过的字符的计数器。
因此,只要一次在循环中一次阅读一个字符,从字符中获取反阵列索引,然后增加正确的元素。无需实际存储您阅读的文本,不需要多个检查循环。
打印时,在数组上循环并打印每个非零的元素,以及其相应的字符。
相关文章:
- 从矢量C++读取字符时出现问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- C++理解计算字符变量的问题
- 将十六进制值设置为用于填充的字符变量时出现问题
- 编写 cin.get() 以接收字符数组时出现问题
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 字符 * 未从重载运算符或内存管理问题正确返回
- 将utf16宽std::wstring转换为utf8窄std::string以获得罕见字符时出现问题
- 我在使用字符的函数时遇到了一些问题
- 用wchar_t处理 unicode 字符好吗?它不会引起任何问题吗?
- 将 c++ 字符串转换为常量字符 * 时出现问题
- C++程序,将整数输入转换为字符的问题
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- C++ 初级面试问题:仅使用字符指针压缩字符序列的功能
- 通过比较字符设置字符串时出现问题
- 我的编辑距离递归代码中的字符类型有问题
- 获取“boost::文件系统::p ath”字符指针时出现问题
- C Unicode UTF-8解码字符的问题
- 类型转换问题:字符数组的元素转换为整数变量