Counting characters in words in a C++ console application

a 夏天 提交于 2019-12-24 12:04:19

问题


This is the problem that I am attempting to solve:

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
...

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.

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).


回答1:


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.



来源:https://stackoverflow.com/questions/17972768/counting-characters-in-words-in-a-c-console-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!