首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >寻找地图技术

寻找地图技术
EN

Stack Overflow用户
提问于 2018-04-25 17:07:20
回答 1查看 59关注 0票数 1

下面是我使用的代码,on.it从字符串中获取单词计数,但现在我一直试图使用映射应用相同的逻辑,但无法这样做,因为在运行时,映射不能取键值,我是否可以每次从字符串中将每个单词存储在不同的键中,这样我就可以得到实际的单词计数,.Any,知道如何做到这一点吗?

代码语言:javascript
复制
 #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();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-25 21:47:12

如何每次从不同键的字符串中将每个单词存储在键中,以便得到实际的单词计数。

这可以按以下方式进行。您甚至可以处理给定句子/字符串中的每个单词(假设每个单词被空格分隔)。

有几件事要注意:

  1. 如果您使用C++,只需使用C++ std库( #include<conio.h>已在您的soln中使用)
  2. 避免使用using namespace std;
  3. 如果要使用std::map<>,则必须包括标题<map>

例如,这里有一个示例测试输出:https://www.ideone.com/KGua1M

代码语言:javascript
复制
#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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50027777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档