Reverse the string using a single array



#include <string.h>

void str_reverse(char *str)
{
    int i = 0, length = 0;


    if (str == NULL) {
        return;
    }
    
    while (str[i++] != '\0') {
        length++;
    }

    for(i=0; i<length/2; i++) {
        str[length] = str[i]; //s-7, h-6, i-5, 
        str[i] = str[length-1-i]; //y-0, e-1, l-2, 
        str[length-1-i] = str[length]; //s-6, h-5, i-4
    }
    str[length] = '\0';

#if 0
    for(i=0; i<length; i++) {
        printf("%c",str[i]);
    }
#endif
    return;
}

int main ()
{
    char name[7] = "Shirley";
    char *rev_name;
    str_reverse(name);
    printf("The reversed string is %s", name);
    return 0;
}

Output:
1
The reversed string is yelrihS


In the above program, as we passed pointer "name", we can get the value of "name" after the function call str_reverse also. But, the reversed string can be a return value of str_reverse as well.

Function returning char pointer

#include <string.h>

char *str_reverse(char *str)
{
    int i = 0, length = 0;


    if (str == NULL) {
        return NULL;
    }
    
    while (str[i++] != '\0') {
        length++;
    }

    for(i=0; i<length/2; i++) {
        str[length] = str[i]; //s-7, h-6, i-5, 
        str[i] = str[length-1-i]; //y-0, e-1, l-2, 
        str[length-1-i] = str[length]; //s-6, h-5, i-4
    }
    str[length] = '\0';

#if 0
    for(i=0; i<length; i++) {
        printf("%c",str[i]);
    }
#endif
    return str;
}

int main ()
{
    char name[7] = "Shirley";
    char *rev_name;
    rev_name = str_reverse(name);
    printf("The reversed string is %s", rev_name);
    return 0;
}


Output:
1
The reversed string is yelrihS




#include <stdio.h>

void reverse_string(char *name)
{
    char temp = '\0';
    int length = strlen(name); 
    int index = 0; 
    
    printf("Length of the string %d\n", length); 

    for (index = 0; index < length/2; index++) {
        temp = name[length -1];   // y e
        name[length -1] = name[index]; // s h
        name[index] = temp; // y e
    }
    name[length] = '\0';
    return;
}

int main()
{
    char name[20] = "shirley";
    reverse_string(name);
    printf("Reversed string %s\n", name);
    return 1;
}

Comments