[英]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()
. 我在strtok()
遇到问题。
You can use a simple sscanf()
: 您可以使用简单的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.