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
    uint8_t number = 0;
    // int count_string = 0, count_comma = 0;
    // while(str[count_string] != '\0'){
    //     count_comma = count_string;
    //     while(str[count_comma] != ',' && str[count_comma] != '\0'){
    //         number = number*10 +  str[count_comma]- '0';
    //         count_comma++;
    //     }
    //     arr[(*count)++] = number;
    //     count_string = count_comma+1;
    //     number = 0;

    // }
    int count_s = 0;
    while(str[count_s] != '\0'){
        if(str[count_s] >= '0' && str[count_s] <= '9')
            number = number * 10 + str[count_s] - '0';
        else if(str[count_s] == ',')
        {
            arr[(*count)++] = number;
            number=0;
        }
        count_s++;

    }
    arr[(*count)++] = number;
}

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