Write a program to accept two strings str1 and str2 and checks whether str2 is rotated version of str1.
Ex. Following are different values of str2 for given str1.
GIVEN:str1=”software”
2-character left rotate
str2=’resoft’
4-character left rotate
str2=’waresoft’
3-character right rotate
str2=’twaresof’
It seems to be bit difficult problem ,but it’s not actually. To solve this problem , We have to append first string to itself. And then check whether second string is present in first or not.
For example:
str1=”software”
str2=”resoft”
so append str1 to itself. Hence now str1=”softwaresoftware” . Now check str2 is present in str1 or not. Str2 is present in str1, hence str2 is rotated version of str1.
Note- You can not use strcat() function of string.h to concatenate a string to itself .Concatenation of string to itself using strcat() function is undefined behavior in C.
Solution using inbuilt function of C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include<stdio.h> #include<string.h> void main() { char str1[200],str2[100]; int len,i,j; printf("Enter first string:"); scanf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}s",str1); printf("Enter second string:"); scanf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}s",str2); len=strlen(str1); for(i=0,j=len;i<len;i++,j++) { str1[j]=str1[i]; } str1[j]='\0'; if(strstr(str1,str2)) { printf("\nstr2 is rotated version of str1"); } else { printf("\nstr2 is NOT rotated version of str1"); } } |
Solution without using inbuilt functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
#include<stdio.h> #include<string.h> int substring(char [],char [] ); void main() { char str1[200],str2[100]; int len,i,j; printf("Enter first string:"); scanf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}s",str1); printf("Enter second string:"); scanf("{b15f91eef52e7c6d40fd3fe45227e26332e4c02be027e4e72c6ecf7adacefb97}s",str2); for(len=0;str1[len]!='\0';len++);//find length of str1 for(i=0,j=len;i<len;i++,j++)//string concatination { str1[j]=str1[i]; } str1[j]='\0'; if(substring(str1,str2)) { printf("\nstr2 is rotated version of str1"); } else { printf("\nstr2 is NOT rotated version of str1"); } } int substring(char a[],char b[] ) { int i,j=0,temp,flag=0,n; for(i=0;a[i]!='\0';) { if(a[i]==b[j]) { if(flag==0) { n=i; flag=1; } i++; j++; } else if(b[j]=='\0') return (1); else { if(flag==1) { i=n+1; j=0; flag=0; } else { i++; } } } if(b[j]=='\0') return 1; else return 0; } |
Josh Software programming test Problem 1
Leave comment if you have any problem with code.
Recent Comments