gpt4 book ai didi

c - strtok() 嵌套时只分词一次

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

假设我有以下字符串:0:1,2,3

我想首先使用 : 作为分隔符进行分隔,当它到达第二部分时(即 1,2,3)并尝试使用 strtok 上(使用 ,)它没有按预期工作。

#include <stdio.h>
#include <stdbool.h>

int main(void){
char s[10];
strcpy(s, "0:1,2,3");
char* token1 = strtok(s, ":");
//To let me know it is on the second part
bool isSecondToken = false;
while (token1) {
printf("token1: %s\n", token1);
if(isSecondToken == true){
char* token2 = strtok(token1, ",");
while (token2) {
printf("token2: %s\n", token2);
token2 = strtok(NULL, " ");
}
}
token1 = strtok(NULL, " ");
isSecondToken = true;
}
}

我得到的输出:

token1: 0
token1: 1,2,3
token2: 1
token2: 2,3

预期输出:

token1: 0
token1: 1,2,3
token2: 1
token2: 2
token2: 3

最佳答案

更新 token1token2 指针时,您需要使用相同的 token 拆分器:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

int main(void){
char s[10];
strcpy(s, "0:1,2,3");
char* token1 = strtok(s, ":");
//To let me know it is on the second part
bool isSecondToken = false;
while (token1) {
printf("token1: %s\n", token1);
if(isSecondToken == true){
char* token2 = strtok(token1, ",");
while (token2) {
printf("token2: %s\n", token2);
token2 = strtok(NULL, ",");
}
}
token1 = strtok(NULL, ":");
isSecondToken = true;
}
}

此外,strcpy 需要 string.h 库,因此您可能还会收到一些隐式声明的警告。

关于c - strtok() 嵌套时只分词一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52467365/

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