这是我正在处理的代码。它从字符串中获取字数,但现在我一直在尝试使用地图来应用相同的逻辑,但是由于地图可以使用地图而不能这样做。 t在运行时获取键值。每次我可以将每个单词从一个字符串中的一个字符串存储在一个不同的键中,这样我就可以获得实际的字数。任何想法我该怎么做?
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
map<string, int> stringCounts;
map<string, int>::iterator iter;
string words;
int TOTAL = 0;
char a[1000];
cout << "enter the string = ";
cin.getline(a, 1000);
int Totalwords = 0;
int no = 0;
for (int i = 0; a[i] != '\0'; i++)
{
if ((int(a[i]) >= 65 && int(a[i]) <= 90) || (int(a[i]) >= 97 && int(a[i]) <= 122))
{
}
else
{
Totalwords++;
}
no = i;
}
TOTAL = Totalwords;
cout << "number of words = " << TOTAL << endl;
string *words = new string[TOTAL];
for (int i = 0, j = 0; j < TOTAL, i <= no;)
{
if ((int(a[i]) >= 65 && int(a[i]) <= 90) || (int(a[i]) >= 97 && int(a[i]) <= 122))
{
words[j] = words[j] + a[i];
stringCounts[words[j]]++;
for (iter = stringCounts.begin(); iter != stringCounts.end(); iter++)
{
cout << "word: " << iter->first << ", count: " << iter->second <<
endl;
}
i++;
}
else
{
j++;
i++;
}
}
_getch();
}
答案 0 :(得分:0)
如何将每个单词存储在不同键中的字符串中 每次这样我才能得到实际的字数。
这可以如下完成。你甚至可以处理给定句子/字符串的每个单词(假设每个单词都用空格分隔)。
有几点需要注意:
#include<conio.h>
已在您的溶液中使用)using namespace std;
std::map<>
,则必须添加标题<map>
例如,这是一个示例测试输出:https://www.ideone.com/KGua1M
#include <iostream>
#include <map>
#include <string>
#include <sstream>
int main()
{
std::string inputString;
std::cout << "Enter the string = ";
std::getline(std::cin, inputString);
std::map<std::string, int> Map; // word, no. of times
size_t wordCount = 0;
size_t letterCount = 0;
std::stringstream sstr(inputString);
std::string word;
while (std::getline(sstr, word, ' '))
{
Map[word]++;
wordCount++;
letterCount += word.size();
}
std::cout << "Total Words: " << wordCount << "\n\n";
std::cout << "Total letters: " << letterCount << "\n\n";
std::cout << "Each words count\n\n" ;
for(const auto& it: Map)
std::cout << it.first << " " << it.second << " times\n";
return 0;
}