程序检查是否有任何字母(a-z)存在于所有字符串(小说列表)中,并打印找到的字母数

program to check is there any alphabet(a-z) exists in all string(list of novels) and print number of alphabets found

本文关键字:打印 字符串 任何字 是否 检查 a-z 存在 小说 程序 于所 列表      更新时间:2023-10-16

你能告诉我在c中查找所有字符串(字符字符串列表)中出现的字母表的过程是什么吗++输出将只返回匹配的值(字母数字)我正在试用这个

      #include <vector>
#include <iostream>
#include <cstdio>
int main()
{
    //setup
    std::vector<int> alphabetCount;
    for (int i = 0; i < 26; ++i)
    {
        alphabetCount.push_back(0);
    }
    //now the interactive bit
    std::cout << "Enter a line of textn";
    std::string line;
    std::getline(std::cin, line);
    for (size_t i = 0; i < line.size(); ++i)
    {
        char currentChar = tolower(line[i]);
        if (isalpha(currentChar))
        {
            ++alphabetCount[currentChar - 'a']; //subtract a, so if currentChar = a, 'a' - 'a' = 0, so its index 0
        }
    }
    for (size_t i = 0; i < alphabetCount.size(); ++i)
    {
        std::cout << "there were " << alphabetCount[i] << " occurences of " << static_cast<char>(i + 'a') << "n"; //add 'a' for the same reason as above, though we have to cast it to a char.
    }
system("pause");
    return 0;
}

但它只返回单个字符串的值,我希望所有字符串的结果

它一次只取一个字符串的原因是因为你要取一个作为输入,你应该制作一个字符串向量并在其中输入。

您在程序中没有多次读取字符串。下面是示例程序,它非常天真地演示了这个过程。不过,循环终止条件可能比我的要好得多。

int main()
{
    //setup
    std::vector<int> alphabetCount;
    for (int i = 0; i < 26; ++i)
    {
        alphabetCount.push_back(0);
    }
    //now the interactive bit
    std::cout << "Enter a line of textn";
    std::string line;
	do{
		std::getline(std::cin, line);
		for (size_t i = 0; i < line.size(); ++i)
		{
			char currentChar = tolower(line[i]);
			if (isalpha(currentChar))
			{
				++alphabetCount[currentChar - 'a']; //subtract a, so if currentChar = a, 'a' - 'a' = 0, so its index 0
			}
		}
	}while(line != "exit");
	--alphabetCount['e' - 'a'];
	--alphabetCount['x' - 'a'];
	--alphabetCount['i' - 'a'];
	--alphabetCount['t' - 'a'];
    for (size_t i = 0; i < alphabetCount.size(); ++i)
    {
        std::cout << "there were " << alphabetCount[i] << " occurences of " << static_cast<char>(i + 'a') << "n"; //add 'a' for the same reason as above, though we have to cast it to a char.
    }
	system("pause");
    return 0;
}