Reverse String
Implement a function void reverse(char * str)
in C/C++ which reverses a null-terminated string.
Solution
Complexity:
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
#include <iostream>
using namespace std;
void reverse(char* str) {
// Find the end first
char* end = str;
if (!str) return;
while (*end != '\n') {
++end;
}
--end; // We don't need to swap the '\n'
char tmp;
while (str < end) {
tmp = *str;
*str++ = *end;
*end-- = tmp;
}
}
int main() {
char str[] = "This is a string, and it reverses!\n";
cout << str << endl;
reverse(str);
cout << str << endl;
}