计算句子中单词的字符数

时间:2017-11-28 10:59:01

标签: c++ string counting

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

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

输出:

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

我在句子中计算了单词的数量但是想要在句子中计算单词的字数。

2 个答案:

答案 0 :(得分:1)

回到Stackoverflow中的older queries ...希望这有帮助!

#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;
}

答案 1 :(得分:0)

#include <iostream>
using namespace std;

int main() {

    string s="hello there anupam";

    int cnt,i,j;

    for(i=0;s[i]!='\0';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]!='\0';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]=='\0') /*if reached the end of string break out */
            break;
        else
            i=j; /*jump i to the next space character */
    }
    return 0;
}

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