tags:

views:

191

answers:

4

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 :)

+2  A: 

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

polygenelubricants
An exact copy of K)
schot
Putting strlen() in a loop's termination condition is a handy way to make a quadratic algorithm out of a linear one. Call it once and store the result in a variable.
ceo
@ceo Haha, that made me smile!
alex
@ceo, yes, it would make it quadratic, if it were actually _in_ the condition section. I think you'll find it's in the initialisation section here.
paxdiablo
@paxdiablo: how right you are. That'll teach me to read the code carefully before I open my fool mouth.
ceo
@ceo I skipped over that too!
alex
+3  A: 

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.]
paxdiablo
This looks great, but I'm not up to pointers yet. Anyway, thanks, it looks efficient.
alex
@alex, I've added a non-pointer version since you're not yet comfortable with pointers.
paxdiablo
Thanks for the edit!
alex
A: 

You'll find some solutions here, including at least one that works without an additional buffer.

jkramer
+1  A: 

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.

nategoose
Hey, this is a great answer, exactly what I was looking for! I realised the first thing shortly after I posted the question, so I made the `for` block empty.
alex
Just a couple of things you may want to attend to. (1) strdup/alloca are not standard C (you should mention this). (2) Both your strdup and your reverse_in_place are buggy (with off-by-one errors). The first doesn't allocate enough space and the second gives you an empty string.
paxdiablo
@paxdiablo: Thanks! Fixed them. `reverse_in_place` without the `- 1` in `j = len -1` would have moved the null terminator to `str[0]` making it an empty string. The `strdup` without the `+ 1` in the call to `malloc` would not have allocated space for the null terminator. I feel silly for having made those errors.
nategoose
@nategoose Thanks for making the edits!
alex