gpt4 book ai didi

c - strtok 表现出不良行为

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:53 24 4
gpt4 key购买 nike

以下是我的代码片段:

int main()
{
char *str[4];
char *ptr;

char Str[25];
char Str1[25];
memset(Str,32,25);
char temp[25];
sprintf(Str,"123;;False;CXL;;true");
printf("Old String [%s]",Str);
ptr = &Str ;
str[0]=strtok(ptr,";");
str[1]=strtok(NULL,";");
str[2]=strtok(NULL,";");
str[3]=strtok(NULL,";");

printf("str[0] =[%s]",str[0]);
printf("str[1] =[%s]",str[1]);
printf("str[2] =[%s]",str[2]);
printf("str[3] =[%s]",str[3]);

//strncpy(temp,str,25);
memcpy(str[0],"345",3);
sprintf(Str1,"%s;%s;%s;%s",str[0],str[1],str[2],str[3]);
printf("New String [%s]",Str1);
return 0;
}

我担心的是为什么它会忽略原始字符串中的“空”值?根据输出,我得到 4 个标记,但实际上我有 6 个带分隔符 ';' 的标记,它忽略了 b/w 中的“空”值,并且不将它们视为单独的标记。

输出是:

Old String [123;;False;CXL;;true]
str[0] =[123]str[1] =[False]str[2] =[CXL]str[3] =[true]
New String [345;False;CXL;true]

是否有我不知道的解决方法?

谢谢!

最佳答案

strsep MAN

The strsep() function is intended as a replacement for the strtok() function. While the strtok() function should be preferred for portability reasons (it conforms to ISO/IEC 9899:1990 ("ISO C90")) it is unable to handle empty fields, i.e., detect fields delimited by two adjacent delimiter characters, or to be used for more than a single string at a time. The strsep() function first appeared in 4.4BSD.

示例

char *t, *str, *save;

save = str = strdup("123;;False;CXL;;true");
while ((t = strsep(&str, ";")) != NULL)
printf("Token=%s\n", t);

free(save);

输出

Token=123
Token=
Token=False
Token=CXL
Token=
Token=true

关于c - strtok 表现出不良行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45834496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com