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) {
    uint16_t num = 0; // Biến tạm để ghép các chữ số
    uint8_t i = 0;

    while (1) {
        char ch = str[i];

        if (ch >= '0' && ch <= '9') {
            // Xây dựng số từ các chữ số liên tiếp
            num = num * 10 + (ch - '0');
        } 
        else if (ch == ',' || ch == '\0') {
            // Khi gặp dấu phẩy hoặc hết chuỗi => lưu số đã hoàn thành
            arr[*count] = (uint8_t)num;
            (*count)++;
            num = 0;

            // Nếu kết thúc chuỗi thì thoát
            if (ch == '\0')
                break;
        }

        i++;
    }
}

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