句子中出现的字母C++

Letter occurrences in an sentence C++

本文关键字:C++ 句子      更新时间:2023-10-16

好的,所以我正在编写下面的函数,该函数打印一个字母在 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个单独的句子(

我得到:

1 2 1 1 1 1 1 1 1 1 1 1 3 10 1 2 1 4 1 2 2 1 14 2 1 1

一个简单的解决方法是替换它:

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] << " ";
}