-4

I tried the below program . I want this

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

Output :

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

I did counting number of word in sentence but I want counting number of character of words in a sentence.

  • 3
    show the code you have tried with – Jack Flamp Nov 28 '17 at 10:59
  • 1
    make 2 variables, 1 as a counter and 1 as a currentWord holder. Append the next char to currentWord and increment counter. When you encounter a space, comma, dot, whatever just print currentWord and counter, then reset both of them and continue. – N. Ivanov Nov 28 '17 at 11:01

2 Answers2

1

Referring back to older queries in Stackoverflow... Hope this helps!

#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;
}
segFaulter
  • 180
  • 9
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;
}

Here is the working demo of what you wanted. I have explained the code in comments.

anupam691997
  • 310
  • 2
  • 8