All submissions

Parse Comma-Separated Integers into an Array

Code

#include <stdio.h>
#include <stdint.h>
#define lim(x,min,max) (x>=min) && (x<(max+1))
#define isDigi(x) lim(x,48,57)
void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    // Your logic here
    int len = 0 ;
    uint8_t res = 0;
    const char *pos = NULL;
    while(*str)
    {
        if(isDigi(*str) && (pos == NULL))
        {
            pos = str;
        }
        else if(*str == ',')
        {
            /* convert string to int */
            res = 0;
            while(str-pos)
            {
                len = str - pos ; 
                int f = 1;
                for(int n = 0 ; n < len-1 ; n++)
                    f*=10;
                res += (*pos-48) * f;
                pos++;
            }
            //printf("%d ",res);
            *arr = res;
             arr++;
             *count+=1;
            //printf("%d ",f);
            pos = NULL;
        }

       


        str+=1;
    }

    if(pos != NULL)
    {
            res = 0;
            while(str-pos)
            {
                len = str - pos ; 
                int f = 1;
                for(int n = 0 ; n < len-1 ; n++)
                    f*=10;
                res += (*pos-48) * f;
                pos++;
            }
           // printf("%d ",res);
            *arr = res;
             arr++;
             *count+=1;
    }


}

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

 

 

 

Loading...

Input

10,20,30

Expected Output

10 20 30