If you have any query feel free to chat us!
Happy Coding! Happy Learning!
There are several ways to reverse a string in C programming language. One of the most simple and straightforward ways is to use two pointers, one pointing to the start of the string, and the other pointing to the end of the string. In each iteration, the two pointers are moved towards each other, swapping the characters they point to, until they meet in the middle of the string.
Here is an example of how to reverse a string using two pointers:
Copy code
#include <string.h>
#include <stdio.h>
void reverse(char* str) {
int n = strlen(str);
int start = 0;
int end = n - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char str[] = "Hello, world!";
printf("Original string: %s\n", str);
reverse(str);
printf("Reversed string: %s\n", str);
return 0;
}
In this example, the reverse()
function takes a string as an argument, and uses two pointers, start
and end
, to reverse the string in place, swapping the characters until they meet in the middle.
Another approach is to use the inbuilt function strrev()
which is not a standard function, its implementation varies based on the compilers.
It's important to note that these method will only reverse the string in place, if you want to keep the original string as is and return the reversed string, you need to create a new array and copy the reversed string to that.
Comments: 0