ninja.stop
ninja.stop

Reputation: 430

undifined sized string split in c without strtok

I have a string:

 char *s = "asdf:jhgf";

I need to split this into two tokens:

token[0] = "asdf";
token[1] = "jhgf"; 

I'm having problems with strtok().

Upvotes: 0

Views: 908

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

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

int main(){
    char *s = "asdf:jhgf";
    char *token[2];
    char *p = strchr(s, ':');
    size_t len1 = p-s, len2 = strlen(p+1);
    token[0] = malloc(len1+1);
    token[1] = malloc(len2+1);
    memcpy(token[0], s, len1);
    token[0][len1]=0;
    memcpy(token[1], p+1, len2+1);
    puts(token[0]);
    puts(token[1]);
    free(token[0]);free(token[1]);
    return 0;
}

Upvotes: 1

unwind
unwind

Reputation: 399861

You can use a simple sscanf():

char token[2][80];

if(sscanf(s, "%[^:]:%s", token[0], token[1]) == 2)
{
  printf("token 0='%s'\ntoken 1='%s'\n", token[0], token[1]);
}

Note that the first conversion is done using %[^:] to scan up until (but not including) the colon. Then we skip the colon, and scan an ordinary string.

Upvotes: 1

Related Questions