Reverse Characters in a String

From Software Engineers Wiki
Jump to: navigation, search

Reverse a string.

Answer

The simple in-place string reversal.

  • find the last character in the string.
  • swap first and last character in the string.
  • move the pointers, and swap second and second last character.
  • do this until the pointer meet in the middole.
#include <stdio.h>

char *str_reverse(char *str)
{
        char *head = str, *tail;
        char tmp;

        for (tail = str; *tail != '\0'; ++tail)
                ;
        --tail;

        while (head < tail) {
                tmp = *head;
                *head++ = *tail;
                *tail-- = tmp;
        }

        return str;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox