97. Parse Comma-Separated Integers into an Array

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>
uint8_t stoui(const char *str, int start, int end) {
    uint8_t value = 0, mul = 1;
    while(start > end) {
        value += (str[start-1] - '0') * mul;
        start--;
        mul *= 10;
    }
    return value;
}
void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    uint8_t index = 0, end = 0;
    while(str[index] != '\0') {
        if(str[index] == ',') {
            arr[*count] = stoui(str, index, end);
            *count += 1;
            end = index + 1;
        } 
        index++;
    }
    arr[*count] = stoui(str, index, end);
    *count += 1;
}

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

 

 

 

Was this helpful?
Upvote
Downvote