gpt4 book ai didi

c - 使用制表符在 C 中拆分字符串,同时检查它是否可以通过空格拆分

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

我希望能够同时按制表符和空格拆分字符串。我正在从文件中读取结构。我使用了以下代码:

while (fgets(lyne,120,filehandle)) {
printf("%s",lyne);
item = strtok(lyne," ");
record[reccount].n_adults = atoi(item);

item = strtok(NULL," ");
record[reccount].n_kids = atoi(item);

item = strtok(NULL," ");
strcpy(record[reccount].day,item);

item = strtok(NULL,"\n");
strcpy(record[reccount].weather,item);

printf("%s\n",record[reccount].day);
reccount++;
}

/* Close file */

fclose(filehandle);

但是,有时不是通过制表符分隔数据,而是一些记录通过空格分隔数据。我如何进行检查才能处理这些情况?

最佳答案

请阅读man 3 strtok

该函数的第二个参数是一个字符串,可以包含一个或多个分隔符。要标记字符串,请调用 strtok 一次将字符串作为第一个参数,然后在返回时将 NULL 作为第一个参数调用 strtokNULL

例如按制表符 空格字符“拆分”:

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

static const char *teststr = "test 123\t456 789";

int main() {
char *str = strdup(teststr);

char *tok = strtok(str, "\t ");
while (tok) {
printf("token: %s\n", tok);
tok = strtok(NULL, "\t ");
}
free(str);
return 0;
}

编译运行:

$ clang -o strtoktest strtoktest.c && ./strtoktest 
token: test
token: 123
token: 456
token: 789

关于c - 使用制表符在 C 中拆分字符串,同时检查它是否可以通过空格拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24254936/

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