Check The Programming Section
In C Programming various ways we can reverse a string or a line. Such as,
using library function strrev() of string.h header file
using character array with an user defined function
#include<stdio.h>
#include<string.h>
int main(){
char info[] = "Learn Programming";
strrev(info);
printf("String after reverse: %s",info);
return 0;
}
In the above program, string.h header file is used to use the library function strrev(), which is take a character array as input and reverse the string.
#include<stdio.h>
#include<string.h>
void stringReverse(char str[], int size){
int i = 0;
int j = size-1;
while(i<j){
char temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
int main(){
char str[] = "Learn Programming";
stringReverse(str,strlen(str));
printf("String After Reverse: %s",str);
return 0;
}
In the above program, the str is passed as argument to the function stringReverse along with its length. Length of the str is calculated using a library function strlen(str). Inside the function two index variable i and j is used and i is pointing at the start index and j is pointing at the last character. While loop will execute till the value of i-th index is less than j-th index and once both of the index is equal menas both the index is pointing to the middle of the character array. Inside the loop i is incremented and j is decremented by 1. Inside the while loop a temporary character variable temp is used to swap the i-th index character with the j-th index character of the array.
#include<stdio.h>
#include<string.h>
void stringReverse(char str[], int i, int j){
if(i<j){
char temp = str[i];
str[i] = str[j];
str[j] = temp;
return stringReverse(str,i+1,j-1);
}
}
int main(){
char str[] = "Learn Programming";
stringReverse(str,0,strlen(str)-1);
printf("String After Reverse: %s",str);
}