我该如何修复我的“for”问题?循环,以便将相同值的多个输出合并为一个输出(按字母将字符串分隔为长度)
我试图将字符串输入分成单独的单词,然后在不使用 find 的情况下确定每个单词的长度,而仅使用下面列出的库。我已经成功创建了一个“for”循环来执行此操作,但是,它单独输出每个单词。我想将具有相同值长度的单词组合成一个输出,但尚未弄清楚。
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string a;
string s;
cout<<"Enter a phrase: "<<endl;
getline(cin, a);
int count=0;
for(int i = 0; i <= a.size(); i++){
if(!isspace(a[i]) && a[i]){
s += a[i];
count;
}
else if(!a[i] || isspace(static_cast<unsigned char>(a[i]))){
count++;
cout << s.length() << " characters long: " << count<<" words."<< endl;
s = "";
}
else{
count=0;
}
}
return 0;
}
示例:
输入:“我希望我可以结合这个”
输出: 1 个字符长:1 个单词。 4 个字符长:2 个单词。 1 个字符长:3 个单词。 5 个字符长:4 个单词。 7 个字符长:5 个单词。 4 个字符长:6 个单词。
I'm trying to separate a string input into individual words, and then determine the length of each word without using find, and while only using the listed libraries below. I've managed to create a 'for' loop that does this, however, it outputs each word individually. I would like to combine words with the same value length into one single output, but haven't been able to figure it out yet.
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string a;
string s;
cout<<"Enter a phrase: "<<endl;
getline(cin, a);
int count=0;
for(int i = 0; i <= a.size(); i++){
if(!isspace(a[i]) && a[i]){
s += a[i];
count;
}
else if(!a[i] || isspace(static_cast<unsigned char>(a[i]))){
count++;
cout << s.length() << " characters long: " << count<<" words."<< endl;
s = "";
}
else{
count=0;
}
}
return 0;
}
example:
input: "I wish I could combine this"
output:
1 characters long: 1 words.
4 characters long: 2 words.
1 characters long: 3 words.
5 characters long: 4 words.
7 characters long: 5 words.
4 characters long: 6 words.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
快速而肮脏的方法是拥有一个数组,即输入字符串 + 1的长度(因为没有单词大于整个字符串)。每个索引将对应于单词长度,您可以相应地增加这些索引。然后在最后只打印非零长度。这样的事情:
A quick and dirty way to do it would be to have an array which is the length of the input string + 1 (since no word could be larger than the entire string). Each index would correspond to a word length, and you could increment those accordingly. Then at the end just print the nonzero lengths. Something like this:
我会使用 std::map 将每个单词的长度映射到该长度的单词数。
像这样:
在线示例
输出:
I would use a
std::map
to map the length of each word to the number of words of that length.Like this:
Online Example
Output: