c++ - 寻找地图技术
问题描述
这是我正在处理的代码。它从字符串中获取字数,但现在我一直在尝试使用地图应用相同的逻辑,但由于地图在运行时无法获取键值而无法这样做。我该怎么做每次将字符串中的每个单词存储在不同键中的键中,以便我可以获得实际的字数。知道我该怎么做吗?
#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();
}
解决方案
如何每次将字符串中的每个单词存储在不同键中的键中,以便获得实际的字数。
这可以如下进行。您甚至可以处理给定句子/字符串的每个单词(假设每个单词都用空格分隔)。
需要注意的几点:
- 如果您使用 C++,只需坚持使用 C++ 标准库(
#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;
}
推荐阅读
- powershell - 如何通过脚本在 Hyper-V 中创建的虚拟机中运行一些脚本(用户名和密码),无需提示
- reactjs - 我在我的反应应用程序中收到此错误“指示是否通过指定其 SameSite 属性在跨站点请求中发送 cookie”
- android - 如何在 Android Chromium 浏览器应用程序中设置代理
- c - fputs() 产生错误的结果
- react-native - 具有多个类别的多选过滤器
- c# - 从 Web 表单的母版页获取表单值
- elasticsearch - 无法在 m1 芯片上运行旧的 elasticsearch(使用rosetta2)
- django - 有没有办法在 django 的 extra_context 字典中使用路径参数?
- python - 'NoneType' 对象没有属性 '_jvm' pandas split
- android - firebase google 登录结果代码始终为 0