Reverse a String in C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

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.

10. String In C

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?