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

前端 未结 30 1885
长发绾君心
长发绾君心 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:27
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdbool.h>
    
    unsigned char * utf8_reverse(const unsigned char *, int);
    void assert_true(bool);
    
    int main(void)
    {
        unsigned char str[] = "mañana mañana";
        unsigned char *ret = utf8_reverse(str,  strlen((const char *) str) + 1);
    
        printf("%s\n", ret);
        assert_true(0 == strncmp((const char *) ret, "anãnam anañam", strlen("anãnam anañam") + 1));
    
        free(ret);
    
        return EXIT_SUCCESS;
    }
    
    unsigned char * utf8_reverse(const unsigned char *str, int size)
    {
        unsigned char *ret = calloc(size, sizeof(unsigned char*));
        int ret_size = 0;
        int pos = size - 2;
        int char_size = 0;
    
        if (str ==  NULL) {
            fprintf(stderr, "failed to allocate memory.\n");
            exit(EXIT_FAILURE);
        }
    
        while (pos > -1) {
    
            if (str[pos] < 0x80) {
                char_size = 1;
            } else if (pos > 0 && str[pos - 1] > 0xC1 && str[pos - 1] < 0xE0) {
                char_size = 2;
            } else if (pos > 1 && str[pos - 2] > 0xDF && str[pos - 2] < 0xF0) {
                char_size = 3;
            } else if (pos > 2 && str[pos - 3] > 0xEF && str[pos - 3] < 0xF5) {
                char_size = 4;
            } else {
                char_size = 1;
            }
    
            pos -= char_size;
            memcpy(ret + ret_size, str + pos + 1, char_size);
            ret_size += char_size;
        }    
    
        ret[ret_size] = '\0';
    
        return ret;
    }
    
    void assert_true(bool boolean)
    {
        puts(boolean == true ? "true" : "false");
    }
    
    0 讨论(0)
  • 2020-11-22 01:27

    With C++ lambda:

     auto reverse = [](std::string& s) -> std::string {
            size_t start = 0, end = s.length() -1;
            char temp;
    
            while (start < end) {
              temp = s[start];
              s[start++] = s[end];
              s[end--] = temp;
            } 
    
            return s;
       };
    
    0 讨论(0)
  • 2020-11-22 01:28

    If you don't need to store it, you can reduce the time spent like this:

    void showReverse(char s[], int length)
    {
        printf("Reversed String without storing is ");
        //could use another variable to test for length, keeping length whole.
        //assumes contiguous memory
        for (; length > 0; length--)
        {
            printf("%c", *(s+ length-1) );
        }
        printf("\n");
    }
    
    0 讨论(0)
  • 2020-11-22 01:31

    Recursive function to reverse a string in place (no extra buffer, malloc).

    Short, sexy code. Bad, bad stack usage.

    #include <stdio.h>
    
    /* Store the each value and move to next char going down
     * the stack. Assign value to start ptr and increment 
     * when coming back up the stack (return).
     * Neat code, horrible stack usage.
     *
     * val - value of current pointer.
     * s - start pointer
     * n - next char pointer in string.
     */
    char *reverse_r(char val, char *s, char *n)
    {
        if (*n)
            s = reverse_r(*n, s, n+1);
       *s = val;
       return s+1;
    }
    
    /*
     * expect the string to be passed as argv[1]
     */
    int main(int argc, char *argv[])
    {
        char *aString;
    
        if (argc < 2)
        {
            printf("Usage: RSIP <string>\n");
            return 0;
        }
    
        aString = argv[1];
        printf("String to reverse: %s\n", aString );
    
        reverse_r(*aString, aString, aString+1); 
        printf("Reversed String:   %s\n", aString );
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 01:32
    #include <algorithm>
    std::reverse(str.begin(), str.end());
    

    This is the simplest way in C++.

    0 讨论(0)
  • 2020-11-22 01:33

    Note that the beauty of std::reverse is that it works with char * strings and std::wstrings just as well as std::strings

    void strrev(char *str)
    {
        if (str == NULL)
            return;
        std::reverse(str, str + strlen(str));
    }
    
    0 讨论(0)
提交回复
热议问题