如何计算特定字母在字符串中出现的次数?(C++)

BIG*_*PPO 2 c++ c++11

我一直在努力完成一项家庭作业,该作业计算字符串中大写字母、小写字母和数字的实例数量。出现在一个字符串中。

我正在使用一个大小为 132 的常量一维数组来存储输入的字符串,我需要使用两个函数。一个需要计算字符串中字母出现的数量,另一个函数将执行类似于上面的输出。我在程序本身的字母计数方面最挣扎。

目前,这就是我目前的家庭作业的大部分内容。这是一项正在进行的工作(当然),因此代码中很可能出现错误。

void LetterCount(char c_input[], int l_count)
{
// code to count letters
}

void CountOut(//not sure what should go here yet until counting gets figured out)
{
// code that handles output
}

int main()
{
    const int SIZE = 132;
    char CharInput[SIZE];
    int LetterCount = 0;
    cout << "Enter a string of up to 132 characters in size: ";
    cin.getline(CharInput, SIZE); 
    cout << "You entered: " << CharInput << endl;

    Count(CharInput);
    CountOut(//not sure what goes here yet);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出将类似于:

  a - 2
  b - 1
  c - 1
  d - 0
  e - 1
Run Code Online (Sandbox Code Playgroud)

等等...

我已经尝试了一些使用 for 循环来计算字母的实验,并看到了函数 gcount() 的一些示例,但我没有得到任何工作。有没有人建议我如何计算输入字符串中的字母?

Mil*_* Lu 5

map 这里是一个非常有效的数据结构

#include <iostream>
#include <map>
using namespace std;

int main(){
    string str = "a boy caught 2 fireflies";
    map<char, int> str_map;
    for(auto x : str) ++str_map[x];
    for(auto x : str_map) cout << x.first << ' ' << x.second << '\n';
}
Run Code Online (Sandbox Code Playgroud)

  • @kmdreko 这是一个简单的修复,通过更改第二个循环来迭代所需的字符,使用每个字符索引到地图中。如果给定的字符尚未插入,它将读回为 0 (3认同)