![]() |
VOOZH | about |
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
To reverse a in C, we can use a 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.
- Declare two pointers,
start(pointing to the beginning)andend(pointing to the end).- Swap the characters at the positions pointed by
startandend.- Increment
startand decrementend.- Repeat steps 2 and 3 until
startis greater than or equal toend.
The below program demonstrates how we can reverse a string in C.
Original string: Hello, World! Reversed string: !dlroW ,olleH
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)