top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to reverse a string char by char using C?

+2 votes
51 views
How to reverse a string char by char using C?
posted May 20, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes
  1. Run a loop from start to end
  2. swap str[start] with str[end]
  3. increase start and decrease end
  4. if start>end break the loop

Code (tested)

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

void reverse_string(char *str)
{
    /* skip null */
    if (str == 0)
    {
        return;
    }

    /* skip empty string */
    if (*str == 0)
    {
        return;
    }

    /* get range */
    char *start = str;
    char *end = start + strlen(str) - 1; /* -1 for \0 */
    char temp;

    /* reverse */
    while (end > start)
    {
        /* swap */
        temp = *start;
        *start = *end;
        *end = temp;

        /* move */
        ++start;
        --end;
    }
}


int main(void)
{
    char s1[] = "QueryHome";

    reverse_string(s1);
    printf("%s\n", s1);
    return 0;
}
answer May 20, 2015 by Salil Agrawal
Similar Questions
+6 votes

Say you are given "Hello World"
Output should be "olleH dlroW"

+3 votes

Please help me to print all permutations of a string in C?

+3 votes

Is it possible if yes can someone share the code in C?

+3 votes

Say the given string is ABC

Output should be ABC ACB BAC BCA CBA CAB

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...