Thursday, 18 April 2013

Find the number of occurence of a character in a string and store it in another array.

#include <stdio.h>

/* Function returns number of times c occurs in a string */
int numTimes(const char *str, const char c){
    int num=0;
    while(*str){
        if(*str == c) num++;
        str++;
    }
    return num;
}

/* Checks for the presence of the character in res array to avoid duplication */
int isPresent(const char *arr, const char c){
    while(*arr){
        if(c == *arr) return 1;
        arr++;
    }
    return 0;
}

int main(){
    char arr[20] = "AAABDDDFF";
    char res[20];
    char check;
    int num, i;
    int j=0;
    for(i=0;*(arr+i);i++){
        check = arr[i];
        if(isPresent(res, check)==0){
            printf("check: %c\n", check);
            res[j++] = check;
            num = numTimes(arr, check);
            check = (char)((int)'0'+num);
            res[j++] = check;
            res[j] = '\0';
        }
    }
    printf("%s\n",res);
    return 0;
}

// Output: A3B1D3F2

No comments:

Post a Comment