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

前端 未结 30 1924
长发绾君心
长发绾君心 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:14
    #include<stdio.h>
    #include<conio.h>
    
    int main()
    {
        char *my_string = "THIS_IS_MY_STRING";
        char *rev_my_string = my_string;
    
        while (*++rev_my_string != '\0')
            ;
    
        while (rev_my_string-- != (my_string-1))
        {
            printf("%c", *rev_my_string);
        }
    
        getchar();
        return 0;
    }
    

    This is optimised code in the C language for reversing a string... And it is simple; just use a simple pointer to do the job...

    0 讨论(0)
  • 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 <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    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;
    }
    
    0 讨论(0)
  • 2020-11-22 01:18

    Read Kernighan and Ritchie

    #include <string.h>
    
    void reverse(char s[])
    {
        int length = strlen(s) ;
        int c, i, j;
    
        for (i = 0, j = length - 1; i < j; i++, j--)
        {
            c = s[i];
            s[i] = s[j];
            s[j] = c;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:18

    Share my code. As a C++ learner, as an option to use swap(), I am humbly asking for comments.

    void reverse(char* str) {
        int length = strlen(str);
        char* str_head = str;
        char* str_tail = &str[length-1];
        while (str_head < str_tail) 
            swap(*str_head++, *str_tail--);
    }
    
    0 讨论(0)
  • 2020-11-22 01:19

    But I think the XOR swap algorithm is the best...

    char str[]= {"I am doing reverse string"};
    char* pStr = str;
    
    for(int i = 0; i != ((int)strlen(str)-1)/2; i++)
    {
        char b = *(pStr+i);
        *(pStr+i) = *(pStr+strlen(str)-1-i);
        *(pStr+strlen(str)-1-i) = b;
    }
    
    0 讨论(0)
  • 2020-11-22 01:21

    If you are using ATL/MFC CString, simply call CString::MakeReverse().

    0 讨论(0)
提交回复
热议问题