Reverse a String In C Using Pointers
In this tutorial, we are going to see how to reverse a string in C using pointers. For example, if a user enters the string “StackHowTo”, it will be “oTwoHkcatS” when reversed. A string that stays the same when reversed is a string named Palindrome.
There are four ways to reverse a string in C, by using for loop, pointers, recursion, or by strrev function.
Reverse a String In C Using Pointers
#include <stdio.h> #include <string.h> int main() { int len, i; char str[100], *startptr, *endptr, ch; printf(" Enter a string: "); gets(str); len = strlen(str); //pointers initialized by str startptr = str; endptr = str; // Move endptr to the last character for (i = 0; i < len - 1; i++) endptr++; for (i = 0; i < len / 2; i++) { // swap character ch = *endptr; *endptr = *startptr; *startptr = ch; // refresh pointers positions startptr++; endptr--; } printf("String after reversing it: %s", str); return 0; }
Output:
Enter a string: StackHowTo String after reversing it: oTwoHkcatS