97. Parse Comma-Separated Integers into an Array

Back To All Submissions
Previous Submission
Next Submission

Code

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

void remove( char *str, int pos){
    while( *str != '\0'){
        str[pos] = str[pos+1];
        pos++;
    }
} // the second function has const they dont want me to change str cant use it

void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
    // Your logic here

    //remove the comma wont work trying different idea

    int i =0;
    int value =0;

    while ( *str != '\0'){
        // // // the problem is 10 is 2 characters not 1 character so logic breask
        // // if ( *str != ',') {
        // //     arr[i] = (uint8_t)*str - '0'; //since (uint8_t)*str gives in asci the real value is - '0'
        // //      i++;
        // //     (*count)++;
        //       }

        //keep udpating until the comma in a way the digit logic meaning first digit is 1 second is 10 third is 100...
        if ( *str >= '0' && *str <= '9')
            value = value *10 + (*str - '0');
            //commit the calculated value
            if ( *str == ',') {
               arr[i]= value; (*count)++; i++; 
               //reset value ot recalculate a number through the digits logic
               value =0; 
            }
              str++;
        }
        
        //last value since it doesnt end with comma 
        //NB we are always storing then moving one move forward ie preindexing
        arr[i] =value;
        (*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