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);

// void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count) {
//     int value = 0,j=0;
//     for(int i=0; str[i]!='\n'; i++){
//         int c = str[i];
        
//         if( c>='0' && c<='9'){
//             value = (value*10) + c-'0';
//         }
//         else if(c==','|| c=='\0'){// then 2nd condtion eliminates the need of adding the last character
//             if( value >=0 && value <=255) {// this is given in questions so check it no matter what
//                 arr[j++] = (uint8_t)value;
//                 (*count)++;
//         }
            
//         value =0;// this needs to be inside the else block
    

//     }

//  if(c=='\0') break;

// }

// combine 2 cchar to make a number, but how we store the indexes
//}

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;
}



// void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count){
//     //extract every char and multipu by 10, add the next char until , is found, if , is found, store at the next arr position

//     int i=0,value =0,j=0;

//     for( i=0;str[i]!='\0';i++){
//         int c = str[i];

//         if(c >='0' && c<='9'){
//             value=(value*10) + c-'0';
//         }
//         else if(c==','|| c=='\0'){
//             if(value>=0 && value<=255){
//                 arr[j++]= (uint8_t)value;// typecast it as arr is uint8

//             }
//             value=0;
//         }

/
//     }

//     *count = j;//need to return j+1 here
// }



void parse_csv_to_array(const char *str, uint8_t *arr, uint8_t *count){
        int i=0,j=0;

        while(str[i]){

            if(str[i]==','){
                j++;
                arr[j]=0;
                i++;
                continue;
            }

            arr[j] =(arr[j]*10) + (str[i]-'0');
            i++;
        }

        (*count)=j+1;

}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10,20,30

Expected Output

10 20 30