How to reverse a C string

H

In this example we delve into a straightforward function designed to reverse a C-string. As we traverse the theoretical realm, it’s crucial to understand that a C string is essentially a character array culminating with the distinctive termination character ‘\0’ at the end of the actual string. To grasp the intricacies, consider that the length of the array housing the actual string should, at most, be one less than the array’s total length, as the final spot is reserved for the termination character. This concept underscores the delicate balance required when manipulating C-strings to ensure seamless operations within the defined boundaries.

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   _   _   _   _
#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;
}
Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags