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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum Etat {MOT_DEDANS, MOT_DEHORS};
int compter_mots(const char *phrase, const char *delim)
{
int nb_mots = 0;
if (phrase != NULL && *phrase != '\0')
{
if (delim != NULL && *delim != '\0')
{
const char *pc = phrase;
enum Etat etat = MOT_DEHORS;
while (*pc != '\0')
{
if (etat == MOT_DEHORS && strchr(delim, *pc) == NULL)
{
nb_mots++;
etat = MOT_DEDANS;
}
else if (etat == MOT_DEDANS && strchr(delim, *pc) != NULL)
{
etat = MOT_DEHORS;
}
pc++;
}
}
}
return nb_mots;
}
int rechercher_mot(char *mot, char **collection)
{
int trouve = 0;
if (mot != NULL && *mot != '\0')
{
if (collection != NULL && *collection != NULL)
{
int i = 0;
while (collection[i] != NULL && trouve == 0)
{
if (strcmp(mot, collection[i]) == 0)
{
trouve = 1;
}
i++;
}
}
}
return trouve;
}
int compter_mots_identiques(const char *phrase1, const char *phrase2)
{
int nb_mots = 0;
if (phrase1 != NULL && *phrase1 != '\0')
{
if (phrase2 != NULL && *phrase2 != '\0')
{
char *tampon_p1 = strdup(phrase1);
if (tampon_p1 != NULL)
{
char *tampon_p2 = strdup(phrase2);
if (tampon_p2 != NULL)
{
int nb_mots_p2 = compter_mots(phrase2, " \n\t") + 1;
char **mots_p2 = malloc(nb_mots_p2 * sizeof *mots_p2);
if (mots_p2 != NULL)
{
char *mot_courant = NULL;
int i = 0;
char *p1 = tampon_p1;
char *p2 = tampon_p2;
mots_p2[i] = strtok_r(phrase2, " \n\t", &p2);
while (mots_p2[i] != NULL)
{
mots_p2[++i] = strtok_r(NULL, " \n\t", &p2);
}
mot_courant = strtok_r(phrase1, " \n\t", &p1);
do
{
if (rechercher_mot(mot_courant, mots_p2) != 0)
{
nb_mots++;
}
mot_courant = strtok_r(NULL, " \n\t", &p1);
}
while (mot_courant != NULL);
free(mots_p2), mots_p2 = NULL;
}
free(tampon_p2), tampon_p2 = NULL;
}
free(tampon_p1), tampon_p1 = NULL;
}
}
}
return nb_mots;
}
int main(void)
{
const char *phrase1 = "111 222 333 444 555 666 777 888 999";
const char *phrase2 = "121 232 343 454 555 666 787 909 090 111 222";
int nb_mots_communs = compter_mots_identiques(phrase1, phrase2);
printf("Il y a %d mot(s) commun(s)\n", nb_mots_communs);
return 0;
} |
Partager