我需要对这种格式的字符串进行分词:
pippo:c:C2,C3,C4:pippo
我该如何使用strtok对此字符串进行分词(一旦完成分词,我不需要该字符串了)?我想将单独的字符存储到char变量中,而不是char*变量。
我需要对这种格式的字符串进行分词:
pippo:c:C2,C3,C4:pippo
我该如何使用strtok对此字符串进行分词(一旦完成分词,我不需要该字符串了)?我想将单独的字符存储到char变量中,而不是char*变量。
如果您只想要 :c: 部分中的 c,并且您知道事物将具有此格式,则无需进行记号化。 您可以简单地执行以下操作:
char c = strchr(str, ':')[1];
该函数定位第一个冒号“:”,并获取其后面的字符。当然,strtok也可以实现:
strtok(str, ":");
char c = strtok(NULL, ":")[0];
这个代码会获取第二个分词,并且获取该单词的第一个字符。通常情况下,如果您想要更深入地处理内容,可能需要使用循环而不是仅此一句。请注意,在此情况下,str缓冲区必须是可写的,而其他情况则不然。
最后,如果“pippo”部分始终具有相同的长度,则可以简单地使用以下方式:
char c = str[6];
str = "pippo:c:C2,C3,C4:pippo"
。strtok()
在两个标记之间获取单个字符,你可以通过检查提取的字符串长度来实现。int main ()
{
char str[] ="pippo:c:C2,C3,C4:pippo";
char * pch;
char winner;
pch = strtok (str,":");
while (pch != NULL)
{
if(strlen(pch) == 1){ // if there's only 1 char we got it
winner = pch[0]; // if there's more than 1 single char of :x: format you
break; // could check for that too here.
}
pch = strtok (NULL, ":");
}
printf("And the winner is: %c\n", winner);
return 0;
}