【问题标题】:Count how many and what letters contains text计算有多少字母和哪些字母包含文本
【发布时间】:2023-02-21 22:52:25
【问题描述】:

我需要计算有多少字母和哪些字母包含输入的文本。 (考虑大小写)

我已经用文本中的数字完成了类似的任务:


int main()
{
    char text[255];
    int count[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    cin.getline(text, 255);

    int i = 0;
    while (text[i] != '\0')
    {
        switch (text[i])
        {
        case '0': ++count[0];
            break;
        case '1': ++count[1];
            break;
        case '2': ++count[2];
            break;
        case '3': ++count[3];
            break;
        case '4': ++count[4];
            break;
        case '5': ++count[5];
            break;
        case '6': ++count[6];
            break;
        case '7': ++count[7];
            break;
        case '8': ++count[8];
            break;
        case '9': ++count[9];
            break;
        }
        ++i;
    }

    for (int i = 0; i < 10; i++)
    {
        cout << endl << '[' << i << "] = " << count[i];
    }

}

但是我想知道是否有一种方法可以不将大小写字母都写成52个大小写。我想我需要使用 ASCII 表,但我不能将它们放在一起。

【问题讨论】:

  • 只需使用std::map
  • 只是++count[text[i]]
  • std::string text; , std::unordered_map&lt;char, int&gt; count; 就这样,问题解决了
  • 但是我想知道是否有一种方法可以不将大小写字母都写成52个大小写。-- 一张地图不仅允许 52 个案例,还允许任意数量的独立字符。如果使用的语言不是英语怎么办?
  • 顺便说一句,确切的骗局:stackoverflow.com/a/38697323/4165552

标签: c++ string char


【解决方案1】:

最简单的方法是使用标准 C 函数isalpha 和标准容器 std;:map&lt;char, size_t&gt;

例如

#include <map>
#include <cctype>

//...

std::map<char, size_t> alpha;

for ( const char *p = text; *p; ++p )
{
    if ( std::isalpha( ( unsigned char )*p ) )
    {
       ++alpha[*p];
    }
}

for ( const auto &item : alpha )
{
    std::cout << item.first << ": " << item.second << '
';
}

【讨论】:

    【解决方案2】:

    您正在写的是直方图,实现起来很简单:

    #include <string>
    #include <map>
    #include <iostream>
    #include <istream>
    #include <ostream>
    #include <format>
    
    int main() {
        std::map<char, int> histogram;
    
        std::string line;
        if(!std::getline(std::cin, line)) {
            return 0;
        }
    
        for(const auto& c : line) {
            ++histogram[c];
        }
    
        //Format may not exist on your compiler yet.
        //Just use your solution of
        //std::cout << "
    [" << c << "]: " << i;
        //instead.
        for(const auto& [c, i] : histogram) {
            std::cout << std::format("
    [{}]: {}", c, i);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      相关资源
      最近更新 更多