Splitting string into individual words
-
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 #include 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. I believe i need s.find_first_not_of but not sure how to incorprate it or if thats even my problem any help?
-
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 #include 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. I believe i need s.find_first_not_of but not sure how to incorprate it or if thats even my problem any help?
Ramper wrote:
...but will not work if it begins with a space...
So just remove leading spaces.
"Approved Workmen Are Not Ashamed" - 2 Timothy 2:15
"Judge not by the eye but by the heart." - Native American Proverb
-
Ramper wrote:
...but will not work if it begins with a space...
So just remove leading spaces.
"Approved Workmen Are Not Ashamed" - 2 Timothy 2:15
"Judge not by the eye but by the heart." - Native American Proverb
-
wish it was that easy, has to be a string with a leading space and multiple spaces between words.
But do you have to have the leading space in the word strings?
-- Painstakingly Drawn Before a Live Audience
-
wish it was that easy, has to be a string with a leading space and multiple spaces between words.
Ramper wrote:
has to be a string with a leading space and multiple spaces between words.
While it's being parsed? That's a very odd requirement indeed.
"Approved Workmen Are Not Ashamed" - 2 Timothy 2:15
"Judge not by the eye but by the heart." - Native American Proverb