Split a String Using Delimiter

Code

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


void split_string(const char *str, char delimiter, char tokens[10][20], uint8_t *count) {
    int i = 0;   // index in input string
    int k = 0;   // token index
    int l = 0;   // character index within token

    while (str[i] != '\0') {
        if (str[i] == delimiter) {
            // End of current token
            tokens[k][l] = '\0';  // null-terminate token
            k++;
            l = 0;                // reset character index
        } else {
            // Copy character into current token
            if (l < 19) {         // prevent overflow
                tokens[k][l] = str[i];
                l++;
            }
        }
        i++;
    }

    // Handle last token (if string doesn't end with delimiter)
    tokens[k][l] = '\0';
    k++;

    *count = k;
}

int main() {
    char str[101];
    char delimiter;
    fgets(str, sizeof(str), stdin);
    scanf(" %c", &delimiter);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') { str[i] = '\0'; break; }
        i++;
    }

    char tokens[10][20];
    uint8_t count = 0;

    split_string(str, delimiter, tokens, &count);

    for (uint8_t i = 0; i < count; i++) {
        printf("%s\n", tokens[i]);
    }

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

cmd1,cmd2,cmd3 ,

Expected Output

cmd1 cmd2 cmd3