Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count number (0-9) occurrences in a string from a txt file in C

Count number (0-9) occurrences in a string from a txt file in C

I created the part that reads the string from the file and saves it as the variable "line"

My idea is to create a table with 10 elements that at the beginning are 0 and for example if I found 2 numbers of 0 it changes the table[1] in 2 or if it founds 1 number of 9 it changes table[10] to 1 but couldn’t implement it

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output of the string "456 890 111111" should be:

Number 1 appears 6 times
Number 1 appears 1 times

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


int main()
{
    char line[255];
    int table[10];
    FILE *f = fopen("input.txt", "r");

    fgets(line, 255, f);
    printf("String read: %s\n", line);

    fclose(f);
    return 0;
}

Updated code:

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


int main()
{
    char line[255];
    unsigned int table[10] = { 0 };
    FILE *f = fopen("input.txt", "r");

    fgets(line, 255, f);
    printf("String read: %s\n", line);

    int n=0;

    for ( char *p = line; *p != '\0'; p++ )
    {
        if ( '0' <= *p && *p <= '9' ) {
            ++table[*p - '0'];
        }

    }


    fclose(f);
    for (int i=0; table[i] < 10; i++) {
        printf("Number", i, "apears", table[i], "times");
    }

    return 0;
}

>Solution :

As the count of a digit can not be negative it is better to declare the array with the element type unsigned int. Also you need to initialize the array with zeroes.

For example

unsigned int table[10] = { 0 };

when in a loop you can count digits in the string. For example

for ( const char *p = line; *p != '\0'; ++p )
{
    if ( '0' <= *p && *p <= '9' )
    {
        ++table[*p - '0'];
    }
}

All digits as characters are represented sequentially without other intermediate symbols.

Pay attention to that indices in arrays start from 0.

After you updated the code in the question then this for loop

for (int i=0; table[i] < 10; i++) {
    printf("Numarul", i, "apare de", table[i], "ori");
}

is incorrect. For starters this condition table[i] < 10 makes no sense. And read the documentation about printf.

At least the loop should look like

for ( int i = 0; i < 10; i++ ) 
{
    printf( "Numarul %d apare de %u ori\n", i, table[i] );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading