All submissions

Parse Comma-Separated Integers into an Array

Easy and Understandable Code

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

void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    bool is_digit = false; //To check if the current element is a digit
    uint8_t num = 0; //To store the current element in the array

    //Traverse through the array
    while(*str){
        //Check if the current element is a number
        if((*str >= '0') && (*str <= '9')){
            num = num*10 + (*str - '0');
            is_digit = true;
        }
        //Handling the ',' element
        else{
            //To check if the previous part has numericals
            if(is_digit){
                arr[(*count)++] = num; 
                //Reset Num to 0
                num = 0;
                //Reset to it is not a digit
                is_digit = false;
            }
        }
        //Increment to traverse through the array
        str++;
    }
    //Handling of last element if it does not end with comma
    if(is_digit) arr[(*count)++] = num;
       
}

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

 

 

 

Loading...

Input

10,20,30

Expected Output

10 20 30