fork download
  1. //http://stackoverflow.com/questions/3780994/string-reversal-in-c
  2.  
  3. #include <iostream>
  4. #include <algorithm>
  5. #include <vector>
  6. #include <string>
  7. #include <sstream>
  8. using namespace std;
  9.  
  10. string test_string = " This is my test string";
  11.  
  12. int main() {
  13. typedef pair <string::size_type,string::size_type> word_boundaries;
  14. typedef vector <word_boundaries> word_boundaries_vector;
  15. word_boundaries_vector words, spaces;
  16.  
  17. bool first_is_char = test_string[0] != ' ';
  18.  
  19. for(string::size_type pos=0; pos != string::npos;) {
  20. bool is_char = test_string[pos] != ' ';
  21. string::size_type pos_end_token = string::npos;
  22.  
  23. if (is_char)
  24. pos_end_token = test_string.find(' ', pos);
  25. else
  26. pos_end_token = test_string.find_first_not_of(' ',pos);
  27.  
  28. //word_boundaries token = make_pair(pos,pos_end_token == string::npos ? string::npos : pos_end_token-pos);
  29. word_boundaries token;
  30. token.first = pos;
  31. token.second = pos_end_token == string::npos ? string::npos : pos_end_token-pos;
  32.  
  33. if (is_char)
  34. words.push_back(token);
  35. else
  36. spaces.push_back(token);
  37.  
  38. pos = pos_end_token;
  39. }
  40.  
  41. stringstream ss;
  42.  
  43. word_boundaries_vector::const_reverse_iterator it_w = words.rbegin();
  44. word_boundaries_vector::const_iterator it_s = spaces.begin();
  45.  
  46. word_boundaries b;
  47.  
  48. if (!first_is_char)
  49. {
  50. b = *it_s++;
  51. ss << test_string.substr(b.first,b.second);
  52. }
  53.  
  54. while(it_w != words.rend() || it_s != spaces.end()) {
  55. if (it_w != words.rend()) {
  56. b = *it_w++;
  57. ss << test_string.substr(b.first,b.second);
  58. }
  59. if (it_s != spaces.end()) {
  60. b = *it_s++;
  61. ss << test_string.substr(b.first,b.second);
  62. }
  63. }
  64.  
  65. string reversed = ss.str();
  66. cout << "Input: '" << test_string << "'" << endl << "Output: '" << reversed << "'" << endl;
  67. }
Success #stdin #stdout 0.01s 2820KB
stdin
Standard input is empty
stdout
Input: ' This   is my test    string'
Output: ' string   test my is    This'