开发者

Help with reversing a string in C

开发者 https://www.devze.com 2023-01-11 01:57 出处:网络
I am trying to reverse a character string in C Here is what I have void reverse(char str[]) { int i = 0;

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 length
    for (i = 0; str[i] != '\0' ; ++i) {
        length = i;
    }

    char reversed[1000];

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

}

I know that reversed contains the string reversed, but I'm not sure how to modify the original str without throwing away data I need.

I also don't know how to set strto reversed without looping again.

Would it be acceptable to do another...

    int m;
    m = 0;

    for (m = 0; m < length ; ++m) {
        str[j] = reversed[j];
    }

Usually I'd say this many loops smells, but I'm also still quite unfamiliar with the language so I'm not sure...

Update

开发者_运维技巧

Thanks for all the answers guys, and I appreciate the edits too!

I ended up going with this...

int main() {

 char str[] = "Reverse me!";

 int length;

 for (length = 0; str[length] != '\0'; length++) {

 }

 printf("length => %d chars\n", length);

 int j, k;
 char c;

 for (j = 0, k = length - 1; j < k; j++, k--) {
  c = str[k];    
  str[k] = str[j];
  str[j] = c;
 } 

 printf("reversed => %s\n", str);

 return 0;
}

Some things I now know...

  • There is a strlen() like in PHP. However, it has not been discussed in the book yet, plus I need to get familiar with null terminated strings.
  • A for loop can assign and do multiple things that are comma separated. I never knew this!

So asking was worthwhile :)


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


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.]


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消