Check whether two Strings are Anagrams
#include
#include
int find_anagram(char [], char []);
int main()
{
char array1[100], array2[100];
int flag;
clrscr();
printf("Enter the string\n");
gets(array1);
printf("Enter another string\n");
gets(array2);
flag = find_anagram(array1, array2);
if (flag == 1)
printf(""%s" and "%s" are anagrams.\n", array1, array2);
else
printf(""%s" and "%s" are not anagrams.\n", array1, array2);
return 0;
}
int find_anagram(char array1[], char array2[])
{
int num1[26] = {0}, num2[26] = {0}, i = 0;
while (array1[i] != '\0')
{
num1[array1[i] - 'a']++;
i++;
}
i = 0;
while (array2[i] != '\0')
{
num2[array2[i] -'a']++;
i++;
}
for (i = 0; i < 26; i++)
{
if (num1[i] != num2[i])
return 0;
}
return 1;
getch();
}
Output
Enter the string
abll
Enter another string
ball
"abll" and "ball" are anagrams.
Enter the string
tall
Enter another string
all
"tall" and "all" are not anagrams.
To Count the Occurence of a Substring in String
#include
#include
#include
char str[100], sub[100];
int count = 0, count1 = 0;
void main()
{
int i, j, l, l1, l2;
clrscr();
printf("\nEnter a string : ");
scanf("%[^\n]s", str);
l1 = strlen(str);
printf("\nEnter a substring : ");
scanf(" %[^\n]s", sub);
l2 = strlen(sub);
for (i = 0; i < l1;)
{
j = 0;
count = 0;
while ((str[i] == sub[j]))
{
count++;
i++;
j++;
}
if (count == l2)
{
count1++;
count = 0;
}
else
i++;
}
printf("%s occurs %d times in %s", sub, count1, str);
getch();
}
OutputEnter a string : prrrogram c prrrogramming
Enter a substring : rr
rr occurs 2 times in prrrogram c prrrogramming
Remove given Word from a String
#include
#include
#include
void main()
{
int i, j = 0, k = 0, count = 0;
char str[100], key[20];
char str1[10][20];
clrscr();
printf("enter string:");
scanf("%[^\n]s",str);
for (i = 0; str[i]!= '\0'; i++)
{
if (str[i]==' ')
{
str1[k][j] = '\0';
k++;
j = 0;
}
else
{
str1[k][j] = str[i];
j++;
}
}
str1[k][j] = '\0';
printf("enter key:");
scanf("%s", key);
for (i = 0;i < k + 1; i++)
{
if (strcmp(str1[i], key) == 0)
{
for (j = i; j < k + 1; j++)
strcpy(str1[j], str1[j + 1]);
k--;
}
}
for (i = 0;i < k + 1; i++)
{
printf("%s ", str1[i]);
}
}
getch();
}
Output
enter string:Welcome to Sanfoundry's C Programming Class, Welcome Again to C class
enter key:Welcome
to Sanfoundry's C Programming Class, Again to C class
No comments:
Post a Comment