Reverse a String Using a Character Array in C
To reverse a string using a character array in C, we need to store the string in an array and swap the characters from both ends until the middle of the string is reached. This can be achieved using a loop and swapping technique or by utilizing built-in functions.
Examples to Reverse a String in C
1. Reverse a String Using a Loop
In this example, we manually reverse a string stored in a character array by swapping characters from both ends using a while loop.
main.c
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int length = strlen(str);
int start = 0, end = length - 1;
// Swap characters from start and end
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char str[] = "hello";
printf("Original String: %s\n", str);
reverseString(str);
printf("Reversed String: %s\n", str);
return 0;
}
Explanation:
- The
reverseString()function takes a character array as input. - We determine the length of the string using
strlen()and initialize two pointers:startat index 0 andendat the last character. - Using a
whileloop, we swap characters from the beginning and end until they meet in the middle. - After swapping, we increment
startand decrementendto move towards the center. - The function modifies the string in place, and we print the reversed string in the
main()function.
Output:
Original String: hello
Reversed String: olleh
2. Reverse a String Using a Recursive Function
In this example, we reverse a string using recursion by swapping the first and last characters and calling the function recursively for the remaining substring.
main.c
#include <stdio.h>
#include <string.h>
void reverseRecursive(char str[], int start, int end) {
if (start >= end)
return;
char temp = str[start];
str[start] = str[end];
str[end] = temp;
reverseRecursive(str, start + 1, end - 1);
}
int main() {
char str[] = "world";
printf("Original String: %s\n", str);
reverseRecursive(str, 0, strlen(str) - 1);
printf("Reversed String: %s\n", str);
return 0;
}
Explanation:
- The
reverseRecursive()function swaps the first and last characters. - The function is called recursively with
start + 1andend - 1untilstartmeets or exceedsend. - When the base condition
start >= endis met, the recursion stops. - The
main()function initializes the string and calls the recursive function with starting index 0 and last indexstrlen(str) - 1.
Output:
Original String: world
Reversed String: dlrow
Conclusion
In this tutorial, we explored different ways to reverse a string using a character array in C:
- Using a loop: Swapping characters from both ends.
- Using recursion: Reversing by recursively swapping characters.
Among these methods, using a loop is the most portable and widely supported approach.
