-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverseCString.cpp
55 lines (38 loc) · 876 Bytes
/
reverseCString.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
using namespace std;
void swap(char* a, char* b) {
char tmp = *a;
*a = *b;
*b = tmp;
}
void reverse(char* string) {
char* oldStart = string; //save starting point of old string
int endIndex;
for(endIndex = 0; ;endIndex++) {
if(string[endIndex] == '\0')
break;
}
char* oldEnd = &string[endIndex - 1];
while(oldEnd > oldStart) {
char tmp = *oldEnd;
*oldEnd = *oldStart;
*oldStart = tmp;
oldEnd--; oldStart++;
}
}
int main() {
char string[] = "this is a test"; //char* is a string literal; use char array instead
for(int i = 0; ; i++) {
if(string[i] == '\0')
break;
cout << string[i];
}
cout << endl;
reverse(string);
for(int i = 0; ; i++) {
if(string[i] == '\0')
break;
cout << string[i];
}
cout << endl;
}