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()
.
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.
#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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.