Program to check whether one string is a rotation of another

Check whether one string is a rotation of another

Today in this article we will learn about the Program to check whether one string is a rotation of another in C language.

Lets understand this with the help of example :- 

  • Input:-

                     String1= ABCDA 

                     String2= DAABC

  • Output:- Yes 

temp = string1.string1 = “ABCDAABCDA ” Since string2 is a substring of temp, string1 and string2 are rotations of each other.

Find Duplicates Characters

Algorithm

  • Take two string as input from the user 
  • Make a function InRotations() that will take string 1 and string 2 as parameters 
  • In the function InRotations store the size of both the string in size1 and size2 variable respectively 
  • If the size of size1 is not equal to size2 then by default its not in rotation. 
  • Create a temp string that will hold the value str1.str1 
  • Using strcat concatenate str1.str1 and store the value in the temp
  • Using strstr (A pointer to the first occurrence in str1 of the entire sequence of characters specified in str2, or a null pointer if the sequence is not present in str1.) returns NULL if the second string is NOT a substring of first string 
  • Then inside the main using if condition check if the string is in rotation and print “Strings are rotations of each other” if its true otherwise print “Strings are not rotations of each other”
Check Whether one string is a Rotation of Another

C Code :-

  #include <string.h>
#include <stdlib.h>
#include <stdio.h>

// Function checks if passed strings (str1 and str2) are rotations of each other
int InRotations(char *str1, char *str2) {

int size1 = strlen(str1);
int size2 = strlen(str2);

char *temp;
void *ptr;

//Check if sizes of two strings are same
if (size1 != size2)
return 0;

// Create a temp string with value str1.str1
temp = (char *)malloc(sizeof(char)*(size1*2 + 1));
temp[0] = "";

strcat(temp, str1);
strcat(temp, str1);

// Now check if str2 is a substring of temp
ptr = strstr(temp, str2);

//strstr returns NULL if the second string is NOT a substring of first string
if (ptr != NULL)
return 1;
else
return 0;
}

// Driver program to test IsRotations
int main()
{

char str1[100],str2[100];
printf("Enter first string : ");
gets(str1);

printf("Enter second string : ");
gets(str2);

if(InRotations(str1, str2))
printf("Strings are rotations of each other");

else
printf("Strings are not rotations of each other");

return 0;
}

Output:-

Enter first string : AACD
Enter second string : ACDA
Strings are rotations of each other
Enter first string : ABAA
Enter second string : ADSA
Strings are not rotations of each other