在C ++控制台应用程序中计算单词中的字符 [英] Counting characters in words in a C++ console application

查看:56
本文介绍了在C ++控制台应用程序中计算单词中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要解决的问题:

要求用户输入一堆想要的单词,直到输入0.之后 计算每个字母在所有单词中出现的次数,并打印出每个字母的列表以及出现的次数.示例:

Ask the user to enter a bunch of words, as many as they want, until they enter a 0. After that, count how many times each letter appears across all the words, and print out a list of each letter and how many times it appears. Example:

Enter word> hello
Enter word> lemon
Enter word> goodbye
Enter word> 0
Letter: h appears 1 times
letter: e appears 3 times
...

到目前为止,我必须将所有单词放在一起,并进行比较.问题在于,在将所有单词放在一起并输入0之后,我无法计算组合字符串中的每个独立字符.我做了一些研究,并且我读过要执行此操作,您需要向量,但是我不知道如何使用它们.

So far I have to put all the words together, and have made comparisons. The problem lies in that, after all the words are put together, and 0 is input, I cannot count each invidual character within the combined string. I did some research, and I've read that to perform this you need vectors, but i do not understand how to use them.

我已经尝试了一个星期以使其正确,但无济于事. C ++与我学过的所有其他语言(至少对我来说)有点不同.

I've been trying at it for a week to get it right, but to no avail. C++ is sort of different from all the other language I have learned (at least for me).

推荐答案

您可以使用 std::unordered_map ,其中字符为键,而计数器为值.对于您阅读的每个字符串,只需对其进行迭代,然后增加对应于地图中字符的值.

You can use an std::unordered_map, with the characters as key and the counter as value. For each string you read, just iterate over it and increase the value corresponding to the character in the map.

这样,您实际上不需要存储单词.

This way you don't actually need to store the words.

这篇关于在C ++控制台应用程序中计算单词中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆