1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <iostream> #include <cstring> template<typename T> void swap(T &c1, T &c2) { // buffer-less swap c1 ^= c2; c2 ^= c1; c1 ^= c2; } void reverse(char *s) { if (s == nullptr || *s == '\0') return; for(auto rear = s + strlen(s) - 1; rear > s; ++s, --rear) { swap(*s, *rear); } } int main() { char s[] = "The quick brown fox jumps over the lazy dog"; std::cout << "Original string: " << s << std::endl; reverse(s); std::cout << "Reversed string: " << s << std::endl; reverse(s); std::cout << "2-Reversed string: " << s << std::endl; return 0; } |
/tmp/reversal
Original string: The quick brown fox jumps over the lazy dog
Reversed string: god yzal eht revo spmuj xof nworb kciuq ehT
2-Reversed string: The quick brown fox jumps over the lazy dog
Original string: The quick brown fox jumps over the lazy dog
Reversed string: god yzal eht revo spmuj xof nworb kciuq ehT
2-Reversed string: The quick brown fox jumps over the lazy dog
No comments:
Post a Comment