77. Parse Comma-Separated Integers into an Array

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

// Parse comma-separated string and fill array with numbers
void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    uint8_t num = 0;
    *count = 0;
    uint8_t i = 0;

    while (str[i] != '\0') {
        if (str[i] >= '0' && str[i] <= '9') {
            // Build number from digits (ASCII to int)
            num = num * 10 + (str[i] - '0');
        } else if (str[i] == ',') {
            arr[(*count)++] = num;
            num = 0;
        }
        i++;
    }

    // Add last number if present
    arr[(*count)++] = num;
}

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;
}

Conceptual Understanding

A CSV (Comma-Separated Value) string like "10,20,30" must be parsed by:

  • Reading each character
  • Building a number using digit-by-digit conversion (digit = ch - '0')
  • Appending number to the array when a comma is found
  • Repeating until end of string
     

Why it’s important in firmware?

  • Many MCUs receive serial commands in CSV format
  • Manual parsing is common in UART/USART-based command shells
  • Avoids bulky tokenizing libraries and gives fine-grained control
  • Also useful for config file or EEPROM read/write processing

Solution Logic

  • Use a loop to scan the string
  • Maintain an accumulator variable (num)
  • On , or \0, store the accumulated value into the array
  • Count how many values were parsed and return it via count

     
Loading...

Input

10,20,30

Expected Output

10 20 30