Help with reversing a string in C

后端 未结 4 1947
无人共我
无人共我 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:14

    Reversing a string in C using pointers

    #include<stdio.h>
    char *srcptr = "Hello!";
    char *destptr;
    unsigned int length = 0;
    void main(void)
    {
       while(*(ptr++) != '\0')
       {
           length++;
       }
       //at the end of while loop, pointer points to end of string 
       while(length--)
       {
            *destptr++ = *ptr--;
       }
        //append null at the end
        *destptr = '\0';
        printf("%s",ptr);
     }
    
    0 讨论(0)
  • 2020-12-12 01:15

    Comments on your code:

    void reverse(char str[]) {
        int i = 0;
    
        int length;
        // Get string length
        for (i = 0; str[i] != '\0' ; ++i) {
            length = i;
        }
    

    Rather than copying the i to length every time you could just wait until the end.

    size_t len = 0; // size_t is an unsigned integer that is large enough to hold the sizes
                    // of the biggest things you can have (32 bits on 32 bit computer,
                    // 64 bits on a 64 bit computer)
    char * s = str;
    while (*s) {
        len++;
        s++;
    }
    

    Though the compiler would probably be able to make this optimization for you.

    You should know, though, that there is a standard string function strlen ( #include <string.h> )which will measure the length of a char string using the same general algorithm (look for the end) but is usually optimized for the target processor.

    len = strlen(str);
    

    Your code again:

        char reversed[1000];
    

    Using big arrays are good for learning and simple examples, but you can also allocate memory dynamically based on the size you now know you need. The standard function for doing this is malloc which is in stdlib.h (also in malloc.h). Memory allocated with this function should also be freed, though.

    int * p = malloc( 8 * sizeof(int) ); // allocate an array of 8 ints
    /* ... work on p ... */
    free(p);
    /* ... don't access the memory pointed to by p anymore ... */
    p = 0;
    

    There are also other functions in the malloc family. There's calloc, which allocates memory and clears sets it to 0. There is also a function called strdup (which isn't in standard C, but is very widely available in string.h) which takes a string and allocates a duplicate of it. It is really just:

    char * strdup(const char * str) {
        size_t len = strlen(str);
        char * s = malloc(len+1);
        if (!s) {
            return s;
        }
        return strcpy(s,str); // This could have been memcpy since you know the size
                              // and memcpy might have been faster on many processors
    }
    

    Another useful memory allocation function is alloca (not in the C standard, but widely available and similar functionality is available with variable length arrays in C99). It is great, but works differently from malloc. It allocates memory that is only useable until the current function returns because this memory is allocated in the same way as memory for local variables (from the stack).

    More of your code:

        int j;
        j = 0;
        // Reverse it
        for (j = 0; j < length ; ++j) {
            reversed[j] = str[length - j];
        }
    

    The code:

    void reverse_in_place(char * str, size_t len) {
       size_t i, j;
       for (i = 0, j = len - 1; i < j ; i++, j--) {
            char a = str[i];
            char z = str[j];
            str[i] = z;
            str[j] = a;
       }
    }
    

    should swap the order of the string without making a copy of it. For strings with odd length it won't try to swap the middle char with itself.

    0 讨论(0)
  • 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 <stdio.h>
    #include <string.h>
    
    // 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.]
    
    0 讨论(0)
  • 2020-12-12 01:35

    You want to do an in-place reversal. Here's a standard algorithm:

    // taken from The C Programming Language
    //    by Brian Kernighan and Dennis Ritchie (K&R)
    void reverse(char s[])
    {
          int c, i, j;
    
          for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
             c = s[i];
             s[i] = s[j];
             s[j] = c;
          }
    }
    

    Note that strlen pretty much replaces your original first loop. It's one of the many standard string manipulation routines available from string.h.

    See also

    • Wikipedia/In-place algorithm
    • Wikipedia/string.h
    • Wikipedia/C Standard Library
    0 讨论(0)
提交回复
热议问题