97. Parse Comma-Separated Integers into an Array

Back To All Submissions
Previous Submission
Next Submission

Code

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

void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    uint8_t cur_val = 0;
    *count = 0;
    uint8_t i =0;

    while(str[i]!='\0'){
        //Check if int value
        if(str[i] >= '0' && str[i] <= '9'){
            //1. Convert ASCII char value to int
            //*10 adds another digit onto end
            //+str[i] - '0' add the next digit
            cur_val = cur_val * 10 + (str[i] - '0');
            //printf("ASCII char value: %u, Converted into int: %u\n",str[i],cur_val);
        }
        else if(str[i]==','){
            //Put current value into array, increment and reset
            arr[*count] = cur_val;
            (*count)++;
            cur_val = 0;
        }
        i++;
    }
    //If no commas present / last value
    //Add last value
    arr[*count] = cur_val;
    (*count)++;


}

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