How do you reverse a string in place in C or C++?

前端 未结 30 1771
长发绾君心
长发绾君心 2020-11-22 00:37

How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string?

30条回答
  •  有刺的猬
    2020-11-22 01:17

    I like Evgeny's K&R answer. However, it is nice to see a version using pointers. Otherwise, it's essentially the same:

    #include 
    #include 
    #include 
    
    char *reverse(char *str) {
        if( str == NULL || !(*str) ) return NULL;
        int i, j = strlen(str)-1;
        char *sallocd;
        sallocd = malloc(sizeof(char) * (j+1));
        for(i=0; j>=0; i++, j--) {
            *(sallocd+i) = *(str+j);
        }
        return sallocd;
    }
    
    int main(void) {
        char *s = "a man a plan a canal panama";
        char *sret = reverse(s);
        printf("%s\n", reverse(sret));
        free(sret);
        return 0;
    }
    

提交回复
热议问题