-
Notifications
You must be signed in to change notification settings - Fork 0
/
(STRING)tocheckwhetertwostringarerotationofeachoytherornot.cpp
57 lines (44 loc) · 1.44 KB
/
(STRING)tocheckwhetertwostringarerotationofeachoytherornot.cpp
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
// C program to check if two given strings are rotations of
// each other
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
/* Function checks if passed strings (str1 and str2)
are rotations of each other */
int areRotations(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);
// This function takes two strings s1 and s2 as an argument and finds the first occurrence of the sub-string s2 in the string s1. The process of matching does not include the terminating null-characters(‘\0’), but function stops there.
/* Now check if str2 is a substring of temp */
ptr = strstr(temp, str2);
free(temp); // Free dynamically allocated memory
/* 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 areRotations */
int main()
{
char *str1 = "AACD";
char *str2 = "ACDA";
if (areRotations(str1, str2))
printf("Strings are rotations of each other");
else
printf("Strings are not rotations of each other");
getchar();
return 0;
}