Reverse a string in C
Reverse a string deal with reverse each character of the entire string. It can be done by user defined function or built-in function.
First, we implement it using the user defined function.
It uses reverse_String() for implementing the function.
👉C Code:
//include the header files
#include <stdio.h>
#include <string.h>
//a user defined function ‘reverse_String()’ is defined
here.
//starting and ending point and temporary variables are
created.
//each character is read and reversed using temp variable.
void reverse_String(char s[]) {
int start = 0;
int end =
strlen(s) - 1;
char temp;
while (start <
end) {
// Exchange
the characters
temp =
s[start];
s[start] =
s[end];
s[end] = temp;
start++;
end--;
}
}
//It creates a character array.
//Get the string from the user
//call the reverse_String() function to reverse the string
//print the reversed String
int main() {
char s[100];
printf("Enter
a string: ");
scanf("%s", s);
reverse_String(s);
printf("Reversed string: %s\n", s);
return 0;
}
𜰘Output:
Enter a string: startItnow
Reversed string: wontItrats
User defined string reverse function is successful.
Next one is built-in functions implementation.
This code uses strlen() built-in function.
𛲣Steps:
- Two char arrays are declared with 100 size. Two integer variables are declared.
- Read the input from the user.
- Find the string length using strlen().
- Reverse the string using a for loop.
- Finally, print the output.
👉Code:
//The header file inclusion
#include <string.h>
#include<stdio.h>
// main() function
char s[100],
rev_s[100];
int i, s_len;
printf("Enter
the string: ");
scanf("%s", s);
s_len =
strlen(s);
for (i = 0; i <
s_len; i++) {
rev_s[i] =
s[s_len - i - 1];
}
rev_s[s_len] =
'\0';
printf("The
Reversed string is: %s\n", rev_s);
return 0;
}
✌Output:
Enter the string: Hiworld
The Reversed string is: dlrowiH
These are the two methods to implement String reverse in C. Hope;
these code segments are useful for you. Keep coding!!!
Comments
Post a Comment