Follow Me on Twitter

Friday, October 30, 2009

Solutions to C Puzzles 6

Given a string s1 and a string s2, write  a snippet to say whether s2 is a
rotation of s1 using only one call to strstr routine?

(eg given s1 = ABCD and s2 = CDAB, return true,
given s1 = ABCD, and s2 = ACBD , return false)

#include
#include

int main ()
{
char *pStr1, *pStr2,*ptempString,*ptr;

pStr1 = "ABCD";
pStr2 = "DABC";
printf("Str1 = \"%s\"\n", pStr1);
printf("Str2 = \"%s\"\n\n", pStr2);

if ((ptempString = malloc(2* strlen(pStr2)+2)) == NULL) {
puts("Memory allocation error!");
exit(0);
}
strcpy(ptempString,pStr2);
strcat( ptempString, pStr2);


if((ptr=strstr(ptempString,pStr1)))
{
puts("true");
}
else
{
puts("false");
}


}

No comments:

Post a Comment