Reverse String
/***
Implement a function void reverse(char *str) in C or C++ which reverses a null-terminated string.
***/
#include<iostream>
using namespace std;
void exchange(char *ch1, char *ch2) {
char t;
t = *ch1;
*ch1 = *ch2;
*ch2 = t;
}
void reverse(char *str) {
char *head, *tail;
head = str;
tail = str;
while(*tail != 'm') tail++;
tail--;
while(head < tail) {
exchange(head, tail);
head++;
tail--;
}
}
Test
void main() {
char str[] = "happym";
cout<<str<<endl;
reverse(str);
cout<<str<<endl;
}
Implement a function void reverse(char *str) in C or C++ which reverses a null-terminated string.
***/
#include<iostream>
using namespace std;
void exchange(char *ch1, char *ch2) {
char t;
t = *ch1;
*ch1 = *ch2;
*ch2 = t;
}
void reverse(char *str) {
char *head, *tail;
head = str;
tail = str;
while(*tail != 'm') tail++;
tail--;
while(head < tail) {
exchange(head, tail);
head++;
tail--;
}
}
Test
void main() {
char str[] = "happym";
cout<<str<<endl;
reverse(str);
cout<<str<<endl;
}
Comments
Post a Comment