gpt4 book ai didi

c - 嵌套strtok_r() : succesive tokens contain parent delimiter

转载 作者:行者123 更新时间:2023-11-30 16:31:23 24 4
gpt4 key购买 nike

给定的字符串具有城市及其距离的键:值对,我使用 strtok_r 首先使用 ";" 分隔符分隔以获得 "city1,1223"并嵌套strtok_r以获得"city1""1223"。在第二个城市之后,嵌套标记与父分隔符一起出现(现在 sTok=243;city3)。

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

#define MAX_CITIES 120

typedef struct {
char *name;
int distance;
} location_s;

int main(void)
{
char *str = "city1,1223;city2,243;city3,500;city4,50";
char *delim = ";";
char *subDelim = ",";

char *endStr;
char *tok, *buf;

location_s *loc[MAX_CITIES];

/* Work around str* str[] conversion */
buf = malloc(strlen(str));
strcpy(buf, str);

tok = strtok_r(buf, delim, &endStr);

int tokenCount = 0, subTokenCount = 0;
while (tok) {
char *lastToken;
char *sTok = strtok_r(tok, subDelim, &lastToken);
loc[tokenCount] = (location_s*)malloc(sizeof(location_s));
while(sTok){
printf("now sTok=%s\n",sTok);
if(subTokenCount == 0) loc[tokenCount]->name = sTok;
if(subTokenCount == 1) loc[tokenCount]->distance = atoi(sTok);

subTokenCount++;
sTok = strtok_r(NULL, subDelim, &lastToken);
}
subTokenCount = 0;
tokenCount++;
tok = strtok_r(NULL, "\n", &endStr);
}

/* Iterating through list of location */
int minDistance = INT_MAX;
int refPoint = 0, j = 0;
int refDistance = minDistance - refPoint;
char *minCity;
for(int i=0; i < tokenCount; i++) {
refDistance = loc[i]->distance - refPoint;
if (refDistance < minDistance) {
minDistance = loc[i]->distance;
j = i;
}
}

minCity = malloc(sizeof(loc[j]->name));
strcpy(minCity, loc[j]->name);

printf("min: %d", minDistance);
printf("\nplace: %s", minCity);
free(minCity);
free(buf);

return 0;
}

我知道 strtok 不是一个可行的解决方案,因为它会丢失先前 token 的上下文,这是终端的输出。

$ ./a.exe
now sTok=city1
now sTok=1223
now sTok=city2
now sTok=243;city3
now sTok=500;city4
now sTok=50
min: 243
place: city2

最佳答案

这项工作是否像克里斯指出的那样,存在拼写错误

Looks like code is doing what you asked and you've got a typo in tok = strtok_r(NULL, "\n", &endStr); which should be tok = strtok_r(NULL, delim, &endStr); - Chris Turner

现在的输出如下:

$ ./a.exe
now sTok=city1
now sTok=1223
now sTok=city2
now sTok=243
now sTok=city3
now sTok=500
now sTok=city4
now sTok=50
min: 50
place: city4

关于c - 嵌套strtok_r() : succesive tokens contain parent delimiter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50646449/

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