97. Parse Comma-Separated Integers into an Array

Back To All Submissions
Previous Submission
Next Submission

Code

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

void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    // Your logic here
    int newc=0;
    int num=0;
    while(*str){
        //printf("%c ",*str);
        newc++;
       // printf("%d",*count);
        if(*str==','){
            newc--;
            *(count)=*(count)+1; // or (*count)++;
            //printf("sdf");
            str-=newc;
            for(int i=newc; i>0; i--){
                int n=(*str)-'0';
                num=num+(n * (pow(10,i-1)));
               // printf("%d ",num);
                str++;
            }
            //printf("\n %d \n",num);
            newc=0;
            arr[*(count)-1]=num;
            num=0;
            //printf("sdf");
        }
        str++;
    }
    str-=newc;
    num=0;
    for(int i=newc; i>0; i--){
        int n=(*str)-'0';
        num=num+(n * (pow(10,i-1)));
               //printf("%d ",num);
                str++;
        }
    //printf("%d",*(count));
    arr[*(count)]=num;
    (*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

 

 

 

Was this helpful?
Upvote
Downvote