How to reverse string without temporary variable in C++

1 Answer

0 votes
#include <iostream>

void ReverseStringWithoutTemporaryVariable(std::string &str) {
    int start = 0, end = str.length() - 1;
   
   while(start < end) {
       str[start] ^= str[end]; // XOR used to swap two variables
       str[end] ^= str[start];
       str[start] ^= str[end];
       start++;
       end--;
   }
}

int main() {
   std::string str = "c++ java c";
   
   ReverseStringWithoutTemporaryVariable(str);
   
   std::cout << str;
}




/*
run:

c avaj ++c

*/

 



answered Aug 21, 2023 by avibootz
edited Aug 21, 2023 by avibootz

Related questions

1 answer 152 views
1 answer 165 views
1 answer 174 views
1 answer 158 views
1 answer 153 views
1 answer 140 views
1 answer 144 views
...