C Program to Reverse a String. Reversing a string is a fundamental programming exercise in C, testing your understanding of basic data structure and manipulation techniques. In this article, we are going to see different approaches to perform string reversal in C.
Table of Contents
C Program to Reverse a String by Two Pointer Swap
This method utilizes to pinter traversing the string from the opposite end. At each iteration, the character pointed to our swap, effectively mirroring the String element by element. this approach requires minimal additional memory and showcases efficient in-place manipulation.
C Program to Reverse a String by Two Pointer Swap
#include <stdio.h>
#include<string.h>
void reverse_string(char *str)
{
int len = strlen(str);
int i = 0, j = len - 1;
char temp;
while (i < j)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
void main()
{
char str[] = "Gang For Code";
reverse_string(str);
printf("Reversed string = %s", str);
}
Output
C Program to Reverse a String by Recursive Mirror
Recursion provides a smart way to reverse a String by breaking it down into smaller reversed parts. It works like this- When we get to the end of the string(“\n”), we stop and start putting the characters together in reversed order. At each step, we add the current character to the part of the string we have reversed so far. It is like solving a puzzle by flipping and attaching pieces until we have the whole picture.
C Program to Reverse a String by Two Pointer Swap
#include <stdio.h>
#include <string.h>
void reverse_string_recursion(char *str, int start, int end)
{
if (start >= end)
{
return;
}
int len = strlen(str);
char temp;
temp = str[start];
str[start] = str[end];
str[end] = temp;
// Recursive call
reverse_string_recursion(str, start + 1, end - 1);
}
void main()
{
char str[] = "Gang For Code";
int len = strlen(str);
reverse_string_recursion(str, 0, len - 1);
printf("Reversed string = %s", str);
}
Output
Happy Coding
2 thoughts on “C Program to Reverse a String”