c++ - How can I reach the second word in a string? -


i'm new here , first question, don't harsh :]

i'm trying reverse sentence, i.e. every word separately. problem can't reach second word, or reach ending of 1-word sentence. wrong?

char* reverse(char* string) {     int = 0;     char str[80];     while (*string)         str[i++] = *string++;     str[i] = '\0'; //null char in end     char temp;     int wstart = 0, wend = 0, ending = 0; //wordstart, wordend, sentence ending     while (str[ending]) /*@@@@this part won't stop@@@@*/     {         //skip spaces         while (str[wstart] == ' ')             wstart++; //wstart - word start         //for each word         wend = wstart;         while (str[wend] != ' ' && str[wend])             wend++; //wend - word ending         ending = wend; //for sentence ending          (int k = 0; k < (wstart + wend) / 2; k++) //reverse         {             temp = str[wstart];             str[wstart++] = str[wend];             str[wend--] = temp;         }     }     return str; } 

your code unidiomatic c++ in doesn't make use of lot of common , convenient c++ facilities. in case, benefit from

here's alternative version uses these facilities:

#include <algorithm> #include <iostream> #include <iterator> #include <sstream> #include <vector>  std::string reverse( const std::string &s ) {     // split string on spaces iterating on stream     // elements , inserting them 'words' vector'.     std::vector<std::string> words;     std::istringstream stream( s );     std::copy(         std::istream_iterator<std::string>( stream ),         std::istream_iterator<std::string>(),         std::back_inserter( words )     );      // reverse words in vector.     std::reverse( words.begin(), words.end() );      // join words again (inserting 1 space between 2 words)     std::ostringstream result;     std::copy(         words.begin(),         words.end(),         std::ostream_iterator<std::string>( result, " " )     );     return result.str(); } 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -