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
    int i = 0;
    int num = 0;

    /*
    Num Logic : 
    suppose number 101, 
    initial condition: num = 0 str[i] = 1
    num = 0 * 10 + ('1' - '0') = 1  (('1' - '0') this is ASCII Difference)
    num = 1 * 10 + ('0' - '0') = 10
    num = 10 * 10 + ('1' - '0') = 101
    Final num before Detecting the comma = 101
    */

    while(str[i] != '\0'){
        if(str[i] >= '0' && str[i] <= '9'){
            num = num * 10 + (str[i] - '0'); //prepare the num
        }
        else if(str[i] == ','){
            arr[*count] = (uint8_t) num; //store the num after detecting the comma
            (*count)++; //increament the count pointer in array
            num = 0; //num = 0 for next string element
        }
        i++;
    }
    arr[*count] = num; //Because after the last element, there wont be any comma so we will store the number outside the loop
    (*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

 

 

 

Upvote
Downvote
Loading...

Input

10,20,30

Expected Output

10 20 30