Reversing a string is nothing but changing the order of characters where last character becomes first character and so on. There are various ways of reversing a string.
Example:Original string : college.
Reversed string : egelloc
- Reverse a string using pointers.( Without using library function)
- Reverse a string using strrev() library function.
Description:
s1 – Original string.
s2 – Reversed string.
p1 – Pointer 1 which points to end of original string s1.
p2 – Pointer 2 which points to beginning of string s2.
‘\0’ – NULL character: which marks the end of string.
Input : String to reverse.
Output : Reverse of that string.
Algorithm : To Reverse a given string using Pointers
STEP 1: STARTSTEP 2: READ the original string which is to be reversed.
READ s1
STEP 3: ASSIGN pointer 1 with address of last character of string s1
p1 = address(last character of s1)
STEP 4: ASSIGN pointer 2 with starting address of string s2
p2 = address( s2)
STEP 5: LOOP until all the characters are stored from last to first
p2 <- p1
INCREMENT pointer p2
p2 = p2 + 1
DECREMENT pointer p1
p1 = p1 – 1
STEP 6: ASSIGN NULL character to the end of string s2
p2 = NULL
STEP 7: PRINT both original and reversed string
PRINT s1, s2
STEP 8: END
Example Program 1: To Reverse a given string using Pointers in C
In the below program we are not using any library function to reverse the string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[100],s2[100];
char *p1,*p2;
printf("Enter a String:\n");
gets(s1);
p1=s1+strlen(s1)-1;
p2=s2;
while(p1>=s1)
{
*p2=*p1;
p2++;
p1--;
}
*p2='\0';
printf("String before reverse: %s\n",s1);
printf("String after reverse: %s",s2);
getch();
}
Output:
Enter a String:ICanTutorials
String before reverse: ICanTutorials
String after reverse: slairotuTnaCI
Example Program 2: To Reverse a string using strrev() library function in C
#include<stdio.h>#include<conio.h>
#include<string.h>
int main()
{
char s[100];
printf ("Enter the string to be reversed: ");
gets(s);
printf ("After reversing the string: %s ", strrev(s));
getch();
return 0;
}
Output:
Enter the string to be reversed: LearningAfter reversing the string: gninraeL
QUIZ:
1] strrev() library function is present in header file.- math.h
- string.h
- stdio.h
- conio.h
- TRUE
- FALSE