void reverseString(char * str)
Arguments:
char * str -- a pointer to a stringDescription:
Reverses the given string str. The function preserves letter cases and white spaces. For example, the reverse string of "the" is "eht", and "Here I am" is "ma I ereH".
Version 1:
void reverseString(char * str)
{
if (str == NULL) return;
char *sp = str;
int len = 0;
while ( *sp != '\0') {
len++;
sp++;
}
char copy[len];
int i,j;
// be careful of the index
// the index of last char in str is (len - 1)
for (i = 0, j = len - 1; i < len; i++, j--) {
copy[i] = str[j];
}
for (i = 0; i < len; i++, str++) {
*str = copy[i];
}
}
Version 2:
After we know the length of the string, we can swap the first half and the second half directly.
We can make the solution a little better. Though it still takes O(n) time because of the first loop.
void reverseString(char * str)
{
if (str == NULL) return;
char *sp = str;
int len = 0;
while ( *sp != '\0') {
len++;
sp++;
}
int i, j;
/*
* we only need to iterate to the middle of the string
* len / 2 takes care of both odd and even cases
*/
for (i = 0, j = len - 1; i < len / 2; i++, j--) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}