97. Parse Comma-Separated Integers into an Array

Back To All Submissions
Previous Submission
Next Submission

Code

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

void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    // Your logic here
    int decades = 0;
    int myResult[3];
    int myLen = strlen(str);
    uint8_t myOnes = 0;
    uint8_t myTens = 0;
    uint8_t myHundreds = 0;

    for (uint8_t myCount = 0; myCount < myLen; myCount++){
        while((*str != 0x00)){
            while((*str != 0x00) && (*str != ',')){
                myResult[decades++] = (*str - 0x30);
                str++;
            }

            switch(decades){
                case 1:
                    myHundreds = 0;
                    myTens = 0;
                    myOnes = myResult[0];                 
                    break;

                case 2:
                    myHundreds = 0;
                    myTens = myResult[0]; 
                    myOnes = myResult[1]; 
                    break;

                case 3:
                    myHundreds = myResult[0]; 
                    myTens = myResult[1]; 
                    myOnes = myResult[2]; 
                    break;

                default:
                    break;
            }

            arr[*count] = ((myHundreds * 100) + (myTens * 10) + myOnes);
            *count = *count + 1;    //another number added to array
            str++;                  //move past the comma
            decades = 0;            //reset the decade counter
        }
    }
}

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