0

Possible Duplicate:
Reversing a string in C

I'm currently switching from C++ to C programming for a project and I haven't done much with Char arrays as strings. I need a function that will read in a pointer to a char array and reverse it. I wrote this in C++, which is pretty easy using the string functions, but I'm a little confused on if there are functions or something else in C that is the best way to do this. Thanks, and I'm not necessarily looking for someone to completely finish the code, but to point me in the right direction. If it's simple one line something feel free, but don't do anything that makes you feel uncomfortable.

#include<stdio.h>
#include<string.h>

void reverseString(char *myString)
{
    //reverse string here
}

int main(void)
{
    char myString[] = "This is my string!";
    reverseString(myString);

    return 0;
}
Community
  • 1
  • 1
trueCamelType
  • 2,198
  • 5
  • 39
  • 76

1 Answers1

3

Simplest way: Loop the string char by char and insert each char to another char array in the reverse order.

Or try this: 2)

void reverse_string(char str[])
{
    char c;
    char *p, *q;

    p = str;
    if (!p)
        return;

    q = p + 1;
    if (*q == '\0')
        return;

    c = *p;
    reverse_string(q);

    while (*q != '\0') {
        *p = *q;
        p++;
        q++;
    }
    *p = c;

    return;
}

3)

if( strlen( str ) > 0 ) {
   char* first = &str[ 0 ];
   char* last = &str[ strlen( str ) - 1 ];
   while( first < last ) {
       char tmp = *first;
       *first = *last;
       *last = tmp;
      ++first;
      --last;

4)

char* strrev( char* s )
  {
  char  c;
  char* s0 = s - 1;
  char* s1 = s;

  /* Find the end of the string */
  while (*s1) ++s1;

  /* Reverse it */
  while (s1-- > ++s0)
    {
    c   = *s0;
    *s0 = *s1;
    *s1 =  c;
    }

  return s;
  }
Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
  • 4
    @axiom "should be redirected" is not a good enough reason for downvoting a valid answer, neither is 'this is not the best way' for doing so. If you always expect everybody to do everything in the best way, you can do that, but only if you're a perfect programmer (something I seriously doubt). –  Dec 10 '12 at 05:54
  • @H2CO3 I am no way even near perfection sir, so your doubts are justified. Sorry if i ever implied that i am perfect. Just that i happen to know a bit about what's being discussed. Neither did i down vote just because it is an exact duplicate. I just didn't like the one sentence solution presented in plain English earlier ( take another array and just copy in reverse) – axiom Dec 10 '12 at 05:57
  • 1
    @axiom Oh, I see. Sorry for disturbin in this case. –  Dec 10 '12 at 05:59