In this post we will learn how to Write a c program to reverse a string using C.
C already has the inbuilt function to reverse the string which is strrev. in this post we will see both the ways to reverse the string which are using strrev and without using it.
C Program to Reverse String Without Using inbuilt Function
/** C Program to Reverse String Without Using inbuilt Function by codebind.com */ #include <stdio.h> #include <string.h> void ReverseString(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[] = "Reverse me!"; char s2[] = "abcde"; char s3[] = "abcd"; char s4[] = "abc"; char s5[] = ""; ReverseString(0); ReverseString(s1); ReverseString(s2); ReverseString(s3); ReverseString(s4); ReverseString(s5); printf("%s\n", s1); printf("%s\n", s2); printf("%s\n", s3); printf("%s\n", s4); printf("%s\n", s5); return 0; } /* OUTPUT: !em esreveR edcba dcba cba */
C Program to Reverse String Using strrev() function
/** C Program to Reverse String Using strrev() function by codebind.com */ #include<stdio.h> #include<string.h> int main() { char name[30] = "Hello"; printf("String before strrev( ) : %s\n",name); printf("String after strrev( ) : %s\n", strrev(name)); return 0; } /* OUTPUT: String before strrev( ) : Hello String after strrev( ) : olleH */
Leave a Reply