How to Reverse a String in C?
In C, a string is a sequence of characters terminated by a null character (\0
). Reversing a string means changing the order of the characters such that the characters at the end of the string come at the start and vice versa. In this article, we will learn how to reverse a string in C.
Example:
Input: char myStr[] = "Hello"; Output: Reversed String: olleH
Reverse a String in C
To reverse a string in C, we can use a two-pointer approach in which we will use two pointers pointing to the first and last index. In every iteration, swap the characters at these positions and move the pointers toward each other until they meet or cross to get the reversed string.
Approach:
- Declare two pointers,
start(
pointing to the beginning)
andend
(pointing to the end).- Swap the characters at the positions pointed by
start
andend
.- Increment
start
and decrementend
.- Repeat steps 2 and 3 until
start
is greater than or equal toend
.
C Program to Reverse a String
The below program demonstrates how we can reverse a string in C.
// C program to reverse a string
#include <stdio.h>
#include <string.h>
int main()
{
// Initialize a string
char str[100] = "Hello, World!";
// pointing to the start of string
char* start = str;
// pointing to the end of string
char* end = str + strlen(str) - 1;
// Print the original string
printf("Original string: %s\n", str);
// Reverse the string
while (start < end) {
// perform swap
char temp = *start;
*start = *end;
*end = temp;
// increment start
start++;
// decrement end
end--;
}
// Print the reversed string
printf("Reversed string: %s\n", str);
return 0;
}
Output
Original string: Hello, World! Reversed string: !dlroW ,olleH
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)