句子中出现的字母C++
Letter occurrences in an sentence C++
好的,所以我正在编写下面的函数,该函数打印一个字母在 3 个句子中出现的次数。当我用字母表的所有字母运行它时,它给了我一个远远偏离的计数。我认为问题在于,即使在 1 行文本完成后,它也会继续索引,即使句子少于 80 个字符,它也会一直上升到 80 个字符。问题是我对如何解决问题有点迷茫。
#include <iostream>
#include "StringProcessing.h"
int main()
{
char input[3][80];
std::cout << "Please enter 3 sentences: ";
for(int i = 0; i < 3; ++i)
std::cin.getline(&input[i][0], 80, 'n');
StringProcessing str(input);
return 0;
}
void StringProcessing::letterOccurrence(char input[3][80])
{
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
int freq[26] = {0};
int i = 0;
while(i < 26)
{
for(int row = 0; row < 3; ++row)
{
for(int col = 0; col < 80; ++col)
{
if(alphabet[i] == input[row][col])
freq[i] += 1;
}
}
i++;
}
for(int i = 0; i < 26; ++i)
std::cout << freq[i] << " ";
}
当给出时:abcdefghi jklmnopqr stuvwxyz(作为3个单独的句子(
我得到:
一个简单的解决方法是替换它:
for(int col = 0; col < 80; ++col)
{
if(alphabet[i] == input[row][col])
freq[i] += 1;
}
有了这个:
int col = 0;
while (input[row][col])
{
if(alphabet[i] == input[row][col])
freq[i] += 1;
++col;
}
getline
会自动以 null 终止它读取的字符串,因此如果input[row][col]
' '
,您可以中断循环。
换句话说,你的字符串即使在句子后面也有字符。
char input[3][80];
这实质上意味着,您声明了一个包含 80 列的 3 行数组,但数据未设置为 '\0'。因此,您不应超过每个句子的长度。
尝试更多类似的东西:
#include <iostream>
#include "StringProcessing.h"
int main()
{
char input[3][80];
std::cout << "Please enter 3 sentences: ";
for(int i = 0; i < 3; ++i)
std::cin.getline(input[i], 80, 'n');
StringProcessing str(input);
return 0;
}
void StringProcessing::letterOccurrence(char input[3][80])
{
int freq[26] = {0};
for(int row = 0; row < 3; ++row)
{
char *sentence = input[row];
for(int col = 0; col < 80; ++col)
{
char ch = sentence[col];
if (ch == ' ') break;
if ((ch >= 'a') && (ch <= 'z'))
freq[ch - 'a']++;
else if ((ch >= 'A') && (ch <= 'Z'))
freq[ch - 'A']++;
}
}
for(int i = 0; i < 26; ++i)
std::cout << freq[i] << " ";
}
相关文章:
- 如何删除peer if else分支中的冗长句子
- 在输入句子时终止 std::out_of_range
- 使用 C++ 验证 NMEA 句子
- 分析包含 NMEA 句子的日志文件C++
- Vscode/C++ - cout 无法输出完整的句子,也无法与整数连接
- 如何理解句子的生命周期始于对e的评估
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- C++从句子中删除给定字符的程序不起作用
- 如何让正则表达式匹配句子中间?
- 如何获取句子中单词的第一个字母*没有*指针,引用等
- 为什么函数的返回类型与实际句子不一致?
- 如何将时间和日期转换为 C 或 C++ 的句子格式?
- 引用 using 声明引入的功能的句子是什么意思?
- C++ 如何从句子中读取和存储值
- 句子转换器在存在新行的情况下不起作用
- 如何输入每个单词在字符串数组中的句子,直到用户按Enter键
- 句子与字符串向量中的每个句子的相似程度
- Flex Lexer 模式匹配句子分隔符/标点符号作为 URL 路径部分
- 用句子从单词打印单词
- 如何在文件中找到单词或句子