How to reverse a C string

H

In this example is a simple function which reverses a C-string. From theory we know that a C string is a char array with the special termination character '\0' in the end of actual string. Basically, the actual string residing in the char array should be at maximum the length of the array minus one (which will be used by the termination character).

For example

char array[10];

Position : 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9
Values   :\0   _   _   _   _   _   _   _   _   _

Position : 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9
Values   : H   E   L   L   O  \0   _   _   _   _

Long story short, below is the function:

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

void str_reverse(char* arg)
{
    if (arg == NULL)
        return;

    if (strlen(arg) == 0 || strlen(arg)==1)
        return;

    for (int i = 0; i < (strlen(arg))/2; i++)
    {
        char t = arg[i];
        arg[i] = arg[(strlen(arg)-1) - i];
        arg[(strlen(arg) - 1) - i] = t;
    }
}

/// Example for Testing the function

int main()
{
    char test0[] = "";
    char test1[] = "1";
    char test2[] = "12";
    char test3[] = "123";
    char test4[] = "1234";
    char test5[] = "12345";

    str_reverse(test0);
    str_reverse(test1);
    str_reverse(test2);
    str_reverse(test3);
    str_reverse(test4);
    str_reverse(test5);

    return 0;
}

4 comments

Categories

Tags