#include <iostream>#include <string>#include <boost/tokenizer.hpp>std::string reverseWordOrder(const std::string& sentence) { boost::tokenizer<> tok(sentence); //create the result string that has words in reversed order std::string result; for(boost::tokenizer<>::iterator beg=tok.begin(); beg!=tok.end(); ++beg){ result = *beg + " " + result; } if (result.length() == 0) return ""; else //take care of the trailing space return result.erase(result.length()-1, result.length());}int main(){ std::cout << reverseWordOrder("Terry is a moron") << std::endl; return 0;}
...but it works (yeah, I'm just too lazy to debug your code)
[edited by - civguy on September 30, 2002 12:20:30 PM]
quote:Original post by hammerstein_02 However, can you answer me this, why did it work for a lot of strings but not for any I had 5 letters in? And it was consistent with these..
i''d say its something to do with your compiler... when i ran your original code on VC++ 5 then, according to what sentence i try, it crashed, gave me a debug assertion error or just printed 255 characters of garbage
Runicsoft -- home of my open source Function Parser and more
There''s one more bug that wasn''t addressed here yet (I think). You need to put newsentence[0] = ''\0''; somewhere in there before you use newsentence. Otherwise it may contain garbage (instead of an empty string) which causes a crash at the first strcat.
#include <iostream>template <typename T>void reverse(T* start, T* end) // assume end is one past the end of the characters you want to swap{ for(;start < --end; ++start) { T temp = *start; *start = *end; *end = temp; }}template <typename T>void reverseWords(T* start, T* end) // assume end is one past the end of the characters you want to swap{ reverse(start, end); T* walker = start; while(walker < end) { while(*walker != T('' '') && walker != end) ++walker; reverse(start, walker); start = ++walker; }}int main(int argc, char* argv[]){ using namespace std; char input[] = "This is my sentence"; cout << input << endl; reverseWords(input, input + sizeof(input) - 1); cout << input << endl;}
That doesn''t actually reverse a sentence, it just prints it out in reverse order. You''d have to do that into a string or stringstream, tidy up the spaces, then write them back to the array in order to do what''s asked.