More
Masterclasses
One can define a string as an assortment of characters followed by a null character.
This article focuses on the different ways C language developers use to reverse a string. Learn the different ways to execute reverse strings in the C programming language. But before we begin, learn what reverse a string in C means.
Let us first know what is Reverse A String In C.
The user's input string, which was sent to your software in a specific order, gets entirely reversed when the reverse of a string algorithm is applied to it. The output, for instance, will be "olleh" if the string is "hello."
The palindrome can be verified using this idea. A string that doesn't change when reversed is called a palindrome. Therefore, a palindrome string will still have the same value even after being reversed.
A user-inputted string can be reversed using various methods using a C program. In the C programming language, a given string can be reversed using the strrev function, without strrev, recursion, pointers, or another string, or displaying it in the opposite order.
Let’s discuss some of the methods to reverse a string in C.: |
To reverse a string using recursion in C, you can define a recursive function that takes the string as input and returns the reversed string. Here's a C program to achieve this:
#include#include int main(void) { char mystrg[60]; int leng, g; // Printing the program name and what the program will do printf("Program in C for reversing a given string n "); printf("Please insert the string you want to reverse: "); // fetch the input string from the user scanf( "%s", mystrg ); // This will find the length of your string with the help of strlen() function of the string.h header file leng = strlen(mystrg); // iterate through each and every character of the string for printing it backward or reverse direction for(g = leng - 1; g >= 0; g--) { printf("%c", mystrg[g]); } return 0; } Output Program in C for reversing a given string Please insert the string you want to reverse: w3schools sloohcs32w …………… Process exited after 7.484 seconds with return value 0 Press any key to continue…
Also read about: What is Arrays in C, and C++ and Advantages and Disadvantages of Arrays in C, C++ and Java
To reverse a string in C using a while loop, you can iterate through the string from both ends and swap the characters until you reach the middle of the string.
Check this example using a while loop in the C programming language to output the reverse of a string.
#include#include int main() { char str1[50], temp; // declare and initialize the size of string array. int i = 0, j =0; printf (" Enter a string to be reversed: "); scanf( "%s", str1); j = strlen (str1) - 1; // get the length of the string // use while loop to define the condition while ( i < j) { // use temp variable to store the characters of str1 temp = str1[j]; str1[j] = str1[i]; str1[i] = temp; i++; // i incremented by 1 j--; // j is decremented by 1 } printf (" The reversed of the string: %s", str1); return 0; } Output Enter a string to be reversed: JAVATPOINT The reversed of the string: TNIOPTAVAJ
A for-loop method is another way we can reverse a string in C. To use this method, we need two pointers—one at the beginning of the index and the other at the index. Then switch the characters, raise the starting pointer, and lower the end pointer. Simply repeat this process until the initial pointer exceeds the end pointer.
C Code: #include#include int main() { char str[100]; printf("Enter a string:"); // read string scanf("%s", str); int length = strlen(str); for(int start =0, end=length-1; start<end; start++,end--) { char temp = str[i]; str[i] = str[j]; str[j] = temp; } printf("The reverse of the string is "%s".n", str); return 0; } Output: Enter a string: hello The reverse of the string is "olleh".
We can also reverse a string in C by recursion function. Recursion, as we are all aware, is a concept in which an operation is performed on a single element, and the recursive function call then returns the modified object.
C Code: #include#include void reverse(char*, int, int); int main() { char a[100]; gets(a); //read string reverse(a, 0, strlen(a)-1); printf("%sn", a); return 0; } void reverse(char *x, int begin, int end) { char c; if (begin >= end) return; c = *(x+begin); *(x+begin) = *(x+end); *(x+end) = c; reverse(x, ++begin, --end); } Output: HeroVired deriVoreH
To reverse a string using pointers in C, you can use two pointers to traverse the string from both ends and swap the characters until you reach the middle of the string. The only difference is that we are utilizing Pointers to segregate the logic from the main program, just like when using recursion to reverse a string. Here's a C program to achieve this:
#include#include // Function to reverse the string // using pointers void reverseString(char* str) { int l, i; char *begin_ptr, *end_ptr, ch; // Get the length of the string l = strlen(str); // Set the begin_ptr and end_ptr // initially to start of string begin_ptr = str; end_ptr = str; // Move the end_ptr to the last character for (i = 0; i < l - 1; i++) end_ptr++; // Swap the char from start and end // index using begin_ptr and end_ptr for (i = 0; i < l / 2; i++) { // swap character ch = *end_ptr; *end_ptr = *begin_ptr; *begin_ptr = ch; // update pointers positions begin_ptr++; end_ptr--; } } // Driver code int main() { // Get the string char str[100] = "SamBali"; printf("Enter a string: %sn", str); // Reverse the string reverseString(str); // Print the result printf("Reverse of the string: %sn", str); return 0; } Output Enter a String: My Name Is Sam Result: maS sI Eman Ym
The stack is one of the most basic data structures that can be utilized for to reverse a string in C. We may use this characteristic to reverse the text because the stack adheres to the Last in, First out principle. The goal is to stack the string items and pop each separately. The popped elements arrive in reverse order in this manner.
C Code: #include#include #define max 100 int top,stack[max]; void push(char x){ // Push(Inserting Element in stack) operation if(top == max-1){ printf("stack overflow"); } else { stack[++top]=x; } } void pop(){ // Pop (Removing element from stack) printf("%c",stack[top--]); } int main() { char str[]="HeroVired"; int len = strlen(str); int i; for(i=0;i<len;i++) push(str[i]); for(i=0;i<len;i++) pop(); return 0; } Output: The reversed string is: deriVoreH
IWe trust that you comprehend the subject and now fully grasp the idea. Enroll in the Data Science and Analytics course by HeroVired to learn more about writing code for complicated outputs.
Get started with HeroVired’s skill-up course to discover and learn in-demand talents on your schedule if you want to improve your skill or perhaps consider taking a new course in this area.
There are multiple ways to reverse a string, The most common approach is to iterate through the string from both ends and swap characters until reaching the middle. The other methods are using the strrev() function, using pointers, recursion, and stack.
In the C programming language, a given string can be reversed by leveraging the strrev function, recursion, pointers, or another string, or by showing it in the opposite order.
The string reverse approach entails flipping the order of the characters in a string so that the beginning and last characters are switched.
The strrev() function, which is available anytime in the string.h library reverses the given string. We only need to provide a string as the function's input because the function's code is already included in the library.
To reverse a string in C, you can use a simple program using strrev method () method, that iterates through the string from both ends and swaps the characters until you reach the middle of the string.
Blogs from other domain
Carefully gathered content to add value to and expand your knowledge horizons