'Union, intersection and difference of 2 sets,using just string functions
I have the following program that finds out the reunion, the intersection and the difference between the sets consisting of 2 strings. In my functions, I treat strings as one-dimensional arrays. I need a program that does the same thing, but that uses the maximum possible string processing functions. I'd be very glad if you could help me, I'm still a beginner. Here's my code below :
#include <stdio.h>
#include <string.h>
void stringToSet(char str[])
{
int i, j, k;
for (i = 0; i < strlen(str); i++)
{
for (j = i + 1; j < strlen(str); j++)
{
if (str[j] == str[i])
{
for (k = j; str[k]; k++)
{
str[k] = str[k + 1];
}
}
}
}
printf("\nThe set is : %s\n", str);
}
void findUnion( char *str1, char *str2)
{
int counter = 0;
char str3[100];
while (str1[counter])
{
str3[counter] = str1[counter];
counter++;
}
for (int i = 0; i < strlen(str2); i++)
{
int flag = 0;
for (int j = 0; j < strlen(str1); j++)
{
if (str2[i] == str1[j])
{
flag = 1;
}
}
if (flag == 0)
{
str3[counter] = str2[i];
counter++;
}
}
str3[counter] = '\0';
printf("\nUnion : ");
(*str3) ? printf("%s", str3): printf("\n Empty set!");
}
void findIntersection(const char *str1, const char *str2)
{
int k = 0;
char str3[100];
for (int i = 0; i < strlen(str1); i++)
{
for (int j = 0; j < strlen(str2); j++)
{
if (str1[i] == str2[j])
{
str3[k] = str1[i];
k++;
}
}
}
str3[k] = '\0';
printf("\nIntersection : ");
(*str3) ? printf("%s", str3): printf("\n Empty set!");
}
void findDifferention(const char *str1, const char *str2)
{
char str3[100];
int l = 0;
for (int i = 0; i < strlen(str1); i++)
{
int flag = 0;
for (int j = 0; j < strlen(str2); j++)
{
if (str1[i] == str2[j])
flag = 1;
}
if (flag == 0)
{
str3[l] = str1[i];
l++;
}
}
str3[l] = '\0';
printf("\nDiference :");
(*str3) ? printf("%s", str3): printf("\n Empty set!");
}
int main()
{
char str1[100];
char str2[100];
printf("String 1 :");
fgets(str1,sizeof str1, stdin);
stringToSet(str1);
printf("String 2 :");
fgets(str2,sizeof str2, stdin);
stringToSet(str2);
findUnion(str1, str2);
findIntersection(str1, str2);
findDifferention(str1, str2);
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
