serd2011

225690437

Jul 28th, 2021
517
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. void reverseStringByWords(char* str, char delim);
  4.  
  5. int main() {
  6.     char str[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor";
  7.     std::cout << str << std::endl;
  8.     reverseStringByWords(str, ' ');
  9.     std::cout << str << std::endl;
  10. }
  11.  
  12. void swap(char* a, char* b);
  13. void reverseString(char* begin, char* end);
  14.  
  15. void reverseStringByWords(char* str, char delim) {
  16.     const size_t size = strlen(str);
  17.     if (size == 0) return;
  18.  
  19.     char* strEnd = str + size;
  20.     reverseString(str, strEnd - 1);
  21.  
  22.     char* iterator = str, *wordBegin = str;
  23.     while (iterator != strEnd) {
  24.         if (*iterator == delim) {
  25.             reverseString(wordBegin, iterator - 1);
  26.             wordBegin = iterator + 1;
  27.         }
  28.         iterator++;
  29.     }
  30.     reverseString(wordBegin, iterator - 1);
  31. }
  32.  
  33. void reverseString(char* begin, char* end) {
  34.     while (begin < end) {
  35.         swap(begin++, end--);
  36.     }
  37. }
  38.  
  39. void swap(char* a, char* b) {
  40.     char c = *a;
  41.     *a = *b;
  42.     *b = c;
  43. }
  44.  
RAW Paste Data