Split a String Using Delimiter

Code

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

int token_str(char *str, char delimiter, char token[10][20]){
    int i = 0; 
    int count_row = 0;
    int count_col = 0;
    while(str[i] != '\0'){
        if(str[i] == delimiter){
            token[count_row][count_col] = '\0';
            count_row++; 
            count_col = 0; 
            i++;
            continue; 
        }
        if(count_col < 19){
            token[count_row][count_col] = str[i];
        }
        count_col++; 
        i++;
    }
    token[count_row][count_col] = '\0';
    return count_row + 1;
}

void reset_token(char token[][20], int row){
    for(int i = 0; i<row; i++){
        for(int j = 0; j<20; j++){
            token[i][j] = '\0';
        }
    }
}

int main(){
    char str[20];
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';
    char delimiter;
    scanf("%c",&delimiter);
    getchar();
    char token[10][20]; 
    reset_token(token, 10);
    int count = token_str(str, delimiter, token); 
    for(int i = 0; i < count; i++){
        printf("%s\n",token[i]);
    }
    return 0;
}   

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

cmd1,cmd2,cmd3 ,

Expected Output

cmd1 cmd2 cmd3