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
| #include <stdio.h>
#include <string.h>
/*On centralise la taille max du mot*/
#define TAILLE_MAX 100
/*On regroupe le char et son nombre d'occurrences*/
struct charEtCompteur
{
char c;
int nbOccur;
};
/*On fait une fonction pour trouver la bonne structure*/
struct charEtCompteur* Trouve(struct charEtCompteur tableau[], size_t nombreCharsComptes, char c)
{
size_t indexCh;
for(indexCh=0 ; indexCh < nombreCharsComptes ; indexCh++)
{
if(tableau[indexCh].c == c)
return &( tableau[indexCh] );
}
return NULL;
}
/*On fait une fonction pour ajouter une occurrence
(elle prend un pointeur vers nombreCharsComptes car elle doit pouvoir le modifier)*/
void Ajoute(struct charEtCompteur tableau[], size_t* pNombreCharsComptes, char c)
{
struct charEtCompteur* pObj;
pObj = Trouve(tableau, *pNombreCharsComptes, c);
if(pObj == NULL)
{
/*Ajoute une nouvelle entree dans le tableau*/
pObj = &tableau[ *pNombreCharsComptes ];
pObj->c = c;
pObj->nbOccur = 0;
(*pNombreCharsComptes)++;
}
/*Ici, pObj n'est jamais nul*/
pObj->nbOccur++;
}
/*On fait une fonction pour l'affichage*/
void Affiche(const struct charEtCompteur tableau[], size_t nombreCharsComptes)
{
size_t indexCh;
for(indexCh=0 ; indexCh < nombreCharsComptes ; indexCh++)
{
if(indexCh != 0)
printf(" ");
printf("%c%d", tableau[indexCh].c, tableau[indexCh].nbOccur);
}
}
int main(void)
{
struct charEtCompteur charsComptes[TAILLE_MAX] = {{0}};
size_t nombreCharsComptes = 0;
char mot[TAILLE_MAX+1] = "";
size_t index;
printf("Saisissez un mot (max %d caractères): ", TAILLE_MAX);
fgets(mot, TAILLE_MAX+1, stdin);
for(index=0 ; mot[index] != '\0' ; index++) /*analyse du mot complet*/
{
char c = mot[index];
/*Saute le \n retourné par fgets*/
if(c == '\n')
continue;
Ajoute(charsComptes, &nombreCharsComptes, c);
}
Affiche(charsComptes, nombreCharsComptes);
} |
Partager