Parse Comma-Separated Integers into an Array

Code

#include <stdio.h>
#include <stdint.h>

void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    // Your logic here
    int index = 0; 
    int hund = 0;
    int tenth = 0;
    int ones = 0; 

    while(str[index] != '\0')
    {   int i = 0; 

        if(str[index] != ',' && str[index] != '\0')
        {
            hund = str[index]-48;
            index++; 
            i++; 
        }
        if(str[index] != ',' && str[index] != '\0')
        {
            tenth = str[index]-48;
            index++; 
            i++; 
        }
        if(str[index] != ',' && str[index] != '\0')
        {
            ones = str[index]-48;
            index++;
            i++;
        }
    
        int result = 0;
        if (i == 1)
            result = hund;
        else if(i == 2)
        {   
            result = 10*hund + tenth;
        }
        else if(i == 3)
            result = 100*hund + 10*tenth + ones; 
        
        arr[*count] = (uint8_t)result; 
        (*count) += 1; 
        hund = 0;
        tenth = 0;
        ones = 0; 
        index++; 
    }
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    uint8_t arr[20];
    uint8_t count = 0;

    parse_csv_to_array(str, arr, &count);

    for (uint8_t i = 0; i < count; i++) {
        printf("%u", arr[i]);
        if(i < count - 1){
            printf(" ");
        }
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10,20,30

Expected Output

10 20 30