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) {
    // Your logic here
    char cur;
    int count_idx = 0;
    int idx = 0;
    int val;
    int tens;
    uint8_t buffer[10];

    for(int i = 0; str[i] != '\0';++i) {

        cur = str[i];
        if (cur >= '0' && cur <= '9') {
            cur -= 48;
            buffer[idx] = cur;
            ++idx;
        }

        if (cur == ',') {
            val = 0;
            tens = 1;
            for(int j = idx-1; j >= 0; --j) {
                val += (buffer[j] * tens);
                tens *= 10;
            }
            // printf("val: %d\n", val);
            arr[*count] = val;
            *count += 1;
            idx = 0;
        }
    }
    val = 0;
    tens = 1;
    for(int j = idx-1; j >= 0; --j) {
        val += (buffer[j] * tens);
        tens *= 10;
    }
    arr[*count] = val;
    *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