top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to reverse a string char by char using C?

+2 votes
272 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 LinkedIn 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

...