All submissions

Parse Comma-Separated Integers into an Array

 

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

void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    // Your logic here
    uint8_t number = 0;          // Current number being built digit by digit
    *count = 0;                  // Initialize count of parsed numbers to 0
    uint8_t index = 0;           // Index to traverse the input string

    while (str[index] != '\0')   //Stop at the null terminator ('\0')
    {
        if (str[index] >= '0' && str[index] <= '9') 
        {
            // Character is a digit - build number from digits (ASCII to int)
            // Multiply current number by 10 to shift left, then add new digit
            // (str[index] - '0') converts ASCII digit to numeric value
            number = number * 10 + (str[index] - '0');
        } 
        else if (str[index] == ',') 
        {
            // Found delimiter - store completed number and reset
            arr[(*count)++] = number;  // Store number and increment count
            number = 0;                // Reset for next number

        }
        // Any other characters (spaces, etc.) are ignored
        // Move to next character
        index++;
    }

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

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

 

 

 

 

Loading...

Input

10,20,30

Expected Output

10 20 30