Help with reversing a string in C

后端 未结 4 1950
无人共我
无人共我 2020-12-12 00:33

I am trying to reverse a character string in C

Here is what I have

void reverse(char str[]) {
    int i = 0;

    int length;
    // Get string lengt         


        
4条回答
  •  暖寄归人
    2020-12-12 01:22

    You can use either of the two methods below, depending on whether you're comfortable with pointers or not. It will also be worthwhile looking at them side-by-side when you satrt learning about pointers so you can better understand how they map to each other.

    This is a full program for testing purposes:

    #include 
    #include 
    
    // The pointer version.
    void reverse1 (char *str) {
        char t;                      // Temporary char for swapping.
        char *s = str;               // First character of string.
        char *e = &(s[strlen(s)-1]); // Last character of string.
    
        // Swap first and last character the move both pointers
        // towards each other. Stop when they meet or cross.
        while (s < e) {
            t = *s;
            *s++ = *e;
            *e-- = t;
        }
    }
    
    // The array version.
    void reverse2 (char *str) {
        char t;                // Temporary char for swapping.
        int s = 0;             // First character of string.
        int e = strlen(str)-1; // Last character of string.
    
        // Swap first and last character the move both pointers
        // towards each other. Stop when they meet or cross.
        while (s < e) {
            t = str[s];
            str[s++] = str[e];
            str[e--] = t;
        }
    }
    

     

    int main (void) {
        char x[] = "This is a string for reversing.";
        printf ("Original: [%s]\n", x);
        reverse1 (x);
        printf ("Reversed: [%s]\n", x);
        reverse2 (x);
        printf ("   Again: [%s]\n", x);
        return 0;
    }
    

    and the output is:

    Original: [This is a string for reversing.]
    Reversed: [.gnisrever rof gnirts a si sihT]
       Again: [This is a string for reversing.]
    

提交回复
热议问题