我想通过';'将字符串拆分成标记。但是我有一个问题,例如一些令牌是空的/ null; 123; 123132 ;;; 232; 232323 ;;;; 1; 所以我不能使用strtok因为合并邻接分隔符。我看到你发布这个解决方案:
include <string.h>
char *data = "this&&that&other";
char *next;
char *curr = data;
while ((next = strchr(curr, '&')) != NULL) {
/* process curr to next-1 */
curr = next + 1;
}
/* process the remaining string (the last token) */
但是我不明白,因为当我做next-1获得firts值时,我只得到价值的第一个字而不是全部价值。 你能帮助我吗?你知道怎么分开这个吗? 我是C ansi的程序员。我在另一篇文章中看到存在一个strsep函数,这似乎正是我所需要的,但在C ansi库中,这个函数不包括在内。 谢谢,抱歉我的英文:)
答案 0 :(得分:0)
我认为这是你想要的: -
#include <stddef.h>
#include <string.h>
#include <stdio.h>
char* mystrsep(char** input, const char* delim)
{
char* result = *input;
char* p;
p = (result != NULL) ? strpbrk(result, delim) : NULL;
if (p == NULL)
*input = NULL;
else
{
*p = '\0';
*input = p + 1;
}
return result;
}
int main()
{
char str[] = "123;123132;;;232;232323;;;;1;";
const char delimiters[] = ";";
char* ptr;
char* token;
ptr = str;
token = mystrsep(&ptr, delimiters);
while(token)
{
printf("%s\n",token);
token = mystrsep(&ptr, delimiters);
}
return 0;
}
答案 1 :(得分:0)
#include <stdio.h>
#include <string.h>
char *strtok_r_noskip(char *str, const char *delims, char **store){
char *p, *wk;
if(str != NULL){
*store = str;
}
if(*store == NULL) return NULL;
//*store += strspn(*store, delims);//skip delimiter
if(**store == '\0') return NULL;
p=strpbrk(wk=*store, delims);
if(p != NULL){
*p='\0';
*store = p + 1;
} else {
*store = NULL;
}
return wk;
}
int main(void){
char data1[] = "this&&that&other";
char *store, *token = strtok_r_noskip(data1, "&", &store);
for(; token ; token = strtok_r_noskip(NULL, "&", &store)) {
printf("\"%s\"\n", token);
}
/* output
"this"
""
"that"
"other"
*/
char data2[] = "123;123132;;;232;232323;;;;1;";
token = strtok_r_noskip(data2, ";", &store);
for(; token ; token = strtok_r_noskip(NULL, ";", &store)) {
printf("\"%s\"\n", token);
}
/* output
"123"
"123132"
""
""
"232"
"232323"
""
""
""
"1"
*/
return 0;
}