Get the number of different characters of a C text [duplicated]

1

I need to make a program in C , in which a word is entered and the number of different characters of a text char[] returns. Example: "holahola" only 4 different characters were used. If there is at least one space, it must be taken into account.

Code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i,j,b,a=0;
    char c[60];
    printf("Ingresa una cadena:\n");
    scanf("%[^\n]",&c);
    fflush(stdin);
    printf("%s",c);
    a=0;
    b=strlen(c);
    for(i=0;i<=b;i++){
        for(j=i+1;j<=b;j++){
            if(c[i]==c[j]){
                a++;
            }
        }
    }
    b=b-a;
    printf("Numero de simbolos: %d",b);
    return 0;
}
    
asked by Cristian Alvarez 19.03.2017 в 01:18
source

1 answer

1

Make an array of 256 numbers, initialized to zero:

char ascii[256];
memset(ascii, 0, sizeof(ascii));

Process the string, increasing the index corresponding to the character:

int i;
char* cadena = "holahola"; /* tambien puedes obtenerla con scanf */
for( i=0 ; i < strlen(cadena); i++ ) {
    ascii[cadena[i]]++; /* segun el CHAR en i, incrementas */
}

Explanation: cadena[i] gets the corresponding byte for each character (a number between 0 and 255) of cadena . Then ascii[cadena[i]] accesses the element in ascii that carries the account of each character and the ++ increases that value. Ex: the value of h (which is 48) at the end of the cycle is two. ascii['h'] == 2 .

Then count the non-zero and you will know the result:

int total=0;
for( i=0; i < 256 ; i++ ) {
  if (ascii[i] > 0) total++;
}

Now you have the total. You could also calculate what is the letter / with more repetitions because you know how many occurrences there are of each character.

    
answered by 19.03.2017 / 01:43
source