计数句子中单词的字符数

Counting number of character of words in a sentence

本文关键字:字符 单词 句子      更新时间:2023-10-16

我尝试了以下程序。我想要这个

string input = "hi everyone, what's up."

输出:

hi = 2
everyone = 8
whats= 5
up = 2

我确实在句子中计数单词数,但我想计数句子中单词的字符数。

参考stackoverflow中的旧查询...希望这会有所帮助!

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    string str("Split me by whitespaces");
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words
    while (ss >> buf)
        cout<< buf<<"="<<buf.length() <<endl;
    return 0;
}
#include <iostream>
using namespace std;
int main() {
    string s="hello there anupam";
    int cnt,i,j;
    for(i=0;s[i]!='';i++)   /*Iterate from first character till last you get null character*/
    {
        cnt=0; /*make the counter zero everytime */
        for(j=i;s[j]!=' '&&s[j]!='';j++)  /*Iterate from ith character to next space character and print the character and keep a count of number of characters iterated */
        {
            cout<<s[j];
            cnt++;
        }
                cout<<" = "<<cnt<<"n";  /*print the counter */

        if(s[j]=='') /*if reached the end of string break out */
            break;
        else
            i=j; /*jump i to the next space character */
    }
    return 0;
}

这是您想要的工作演示。我已经在评论中解释了代码。