Cracking the Coding Interview Q1.2

Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.

 

#include<stdio.h>
#include<string.h>

/**
 * reverse the string in place.
 */
void reverse(char* str) {
    if (str == NULL)
        return;
    int n = strlen(str);
    char tmp;
    //be careful: i<n/2, not i<=n/2;
    for (int i = 0; i < n / 2; i++) {
        tmp = str[i];
        str[i] = str[n - 1 - i];
        str[n - 1 - i] = tmp;
    }
    return;
}

int main() {
    char str[10] = "abcde";
    reverse(str);
    printf("%s\n", str);

}
View Code

 

Solution:

void reverse(char *str) {
    char * end = str;
    char tmp;
    if (str) {
        while (*end) {
            ++end;
        }
        --end;
        while (str < end) {
            tmp = *str;
            *str++ = *end;
            *end-- = tmp;
        }
    }
}
View Code

 

 

posted @ 2014-07-03 09:31  jdflyfly  阅读(127)  评论(0编辑  收藏  举报