I have written an isRotation
function that calls on isSubstring
only once(I am allowed to call it only once). I have implemented my own version of isSubstring as well. Any advice is much welcome!
//Checks if one string is a rotation of the other
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isRotation(char *, char *);
bool isSubstring(char *, char *);
int main(int argc, char **argv)
{
if(argc == 3)
{
printf("%s %s a rotation of %s.\n", argv[2], isRotation(argv[1], argv[2])
? "is" : "is not", argv[1]);
}
else
{
fprintf(stderr, "Incorrect number of inputs\n");
return -1;
}
return 0;
}
bool isRotation(char* s1, char* s2)
{
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
if(len1 != len2 || len1 == 0 || len2 ==0)
return 0;
char s3[len2*2];
bool secondCopy = false;
int j = 0;
/*copying 2*s2 into s3. If s2 is a rotation of s1,
then s1 has to be found somewhere inside s3.*/
for(size_t i = 0; i < (2*len2); i++)
{
s3[i] = s2[j];
if(s2[j+1] == '\0' && secondCopy == false)
{
secondCopy = true;
j = 0;
continue;
}
j++;
}
s3[len2*2] = '\0';
//pass the longer string to the first param
return isSubstring(s3, s1);
}
bool isSubstring(char* s1, char* s2)
{
//is s2 a substring of s1?
size_t len2 = strlen(s2);
if(len2 == 0)
return true;
int j = 0;
int i = 0;
while(s1[i] != '\0')
{
if(s2[j] == s1[i])
j++;
i++;
}
return j == len2;
}