By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,856 Members | 1,986 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,856 IT Pros & Developers. It's quick & easy.

Splitting string into words and displaying

P: 12
I need to Write a function that will, given an input string containing many words, split that string into individual words. For each word, the function should output the word, its starting index in the string, and its length to the console without using stream extraction operator.

#include <iostream>
#include <string>
using namespace std;
int main()
{

string sval = " The quick brown fox jumps over the lazy dog";

int cnt=1;
int nsep = sval.find(" ");
while (nsep > 0) {
cout << "Word " << cnt << "="
<< sval.substr(0,nsep) << endl;
cnt = cnt + 1;
sval = sval.substr(nsep+1);
nsep = sval.find(" ");

}
cout << "Word " << cnt << "=" << sval << endl;

#ifdef WIN32
system("pause");
#endif
return(0);
}


Thats where i am so far, it will just split it into words but will not work if it begins with a space or if there is more than 1 space between words.

any help?
Nov 2 '06 #1
Share this Question
Share on Google+
3 Replies


P: 12
I think i need to use the s.find_first_not_of but not sure how to incorporate.
Nov 2 '06 #2

Ganon11
Expert 2.5K+
P: 3,652
Make a function that takes a string variable by reference as its argument, and have it remove all blanks from the start of the string. This will eliminate the problem of a string starting with spaces and multiple spaces seperating words. Call this function before you extract a word.
Nov 2 '06 #3

P: 6
Hi,

Try this code...
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5. char str[] = "The quick brown fox jumps over the lazy dog" ;
  6. int i,prev,w_len;
  7. prev = w_len = 0;
  8. for(i=0;i<sizeof(str);i++)
  9. {
  10. if(str[i] == ' ' || str[i] == '\0' )
  11. {
  12. w_len = (i - prev);
  13. printf("\t%d\t%d\t\n", i,w_len);
  14. prev = i +1 ;
  15. }
  16. else
  17. printf("%c",str[i]);
  18. }
  19.  
  20. return 0;
  21. }
  22.  
~David
Nov 3 '06 #4

Post your reply

Sign in to post your reply or Sign up for a free account.