In the world of computer programming, manipulating strings is a fundamental skill that every programmer must master. One common task in String manipulation is reversing a String, a process where characters of strings are re-arranged in reverse order. In this article, we will explore various methods to write a C program for reverse string.
Table of Contents
Reverse String by Using Array
The most straightforward method for reverse string involves the use of a temporary array to store the reverse string. Let’s write a C program for a reverse string by using an array.
#include <stdio.h>
#include <string.h>
void reverseString(char *str)
{
int length = strlen(str);
char temp[length];
for (int i = 0; i < length; i++)
{
temp[i] = str[length - 1 - i];
}
// Copy reverse String in the original string
strcpy(str, temp);
}
void main()
{
char string[] = "Original String";
printf("Original string = %s\n", string);
reverseString(string);
printf("Reverse string = %s\n", string);
}
Output
Reverse String by using in-place Reversal
For situations where memory efficiency is crucial, we can use in-place reversal to reverse a string. In this method, we swap characters from the beginning and end of the string and move toward the center. Let’s write a C program to reverse a string by using in-place reversal.
#include <stdio.h>
#include <string.h>
void reverseString(char *str)
{
int end = strlen(str) - 1;
int start = 0;
while (start < end)
{
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
void main()
{
char string[] = "Original String";
printf("Original string = %s\n", string);
reverseString(string);
printf("Reverse string = %s\n", string);
}
Output
The in-place method for string reversal uses a two-pointer system to swap characters, progressively moving towards the center of the sring.
Happy Coding
1 thought on “C Program for Reverse String”