给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
Given an array of words and a string, how can I count all words in a given string
给定一个单词数组和一个字符串,我需要计算给定字符串中存在的所有单词。
我已经拆分了句子并将单词包含在哈希图中。但是,当我遍历字符串数组以检查该单词是否存在时,我得到的输出不正确。如何纠正代码?
#include<bits/stdc++.h>
using namespace std;
void countwords(string str,string words[],int n )
{
map<string ,bool > m1; //map
map<string ,bool > ::iterator it;
int i=0,cnt=0;
string temp = " ";
while(i<str.size()) // splitting of sentence into words
{
while(str[i]!=' '&&i<str.size()&&str[i]!='.') // if it doesnt encounter space, add it to temp
{
temp+=str[i];
i++;
}
m1[temp]=true; // insert temp into map
temp=" ";
i++;
}
for(i=0;i<n;i++)
{
if(m1.find(words[i])!=m1.end()&&m1[words[i]]==true) // if word is present in the map increment count & it isn't a duplicate
{
cnt++;
m1[words[i]]=false;
}
}
cout<<cnt;
}
你的代码存在一些问题。
1- temp = " " ,您需要将 temp 设置为空字符串,否则 find(( 函数将不起作用
2-使用map,您将在map中只有一个单词的实例,因此您需要保留每个单词的计数。
下面的代码计算并打印给定数组的字数,对代码的更改最少:
void countwords(string str,string words[],int n ){
map<string ,int > m1;
int i=0, cnt=0;
string temp = "";
while(i < str.size())
{
while(str[i]!=' ' && i<str.size() && str[i]!='.')
{
if(str[i]!=' ' && str[i]!='.')
temp+=str[i];
i++;
}
auto iii = m1.find(temp);
int count = 0;
if(iii != m1.end())
count = iii->second;
count+=1;
m1[temp]=count;
temp="";
i++;
}
for(int i=0; i != n; i++)
{
auto found = m1.find(words[i]);
if(found != m1.end())
std::cout << found->first << " " << found->second << std::endl;
else cout << words[i] << " " << "0" << std::endl;
}}
相关文章:
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- C++-字符串是否包含一个带有简单循环的单词
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 替换字符串中的单词,但忽略引号中的单词
- 替换字符串位置 X 中的单词C++
- 视觉C++使用 map 来比较字符串中的每个单词
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 输出返回编号。等于输入字符串的单词的字符串数
- 在字符串的每个单词的末尾插入字符串
- 分析字符串中的双精度和单词
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 从文件 (C++) 输入两个单词字符串
- 在一行中输入具有其他输入类型的多个单词字符串
- 打印以 "a" 开头的单词(字符串中)
- 如何让我的代码以不会切断单词(字符串)的方式运行?
- 句子变成单词c++字符串