Program in C
Write a function that replaces the contents of a string with the string reversed.
Code:
#include <stdio.h>
//Here is the actual function for the question
void str_reverse(char *str){
int len=0;
//calcualting length
while(str[len]!='\0'){
len++;
}
int front=0,rare=len-1;
//inplace string reverse
//replacing the first and last character of the string
while(front<rare){
char temp=str[front];
str[front]=str[rare];
str[rare]=temp;
//repeating the process untill front and rare crosses each other
front++;
rare--;
}
}
//Here is the test question
int main(void) {
char s[100];//creating a string
printf("Enter a string:");
scanf("%s",s);
str_reverse(s);//passing it the function
printf("Same string after passing to the function str_reverse\n");
printf("%s\n",s);
printf("Contents of the string has been changed");
return 0;
}
Snapshot:
Sample run:
Enter a string:samantha
Same string after passing to the function str_reverse
ahtnamas
Please give it thumbsup and comment below for any problem in the answer
Get Answers For Free
Most questions answered within 1 hours.