gpt4 book ai didi

c - 如何从文本行获取特定数据

转载 作者:行者123 更新时间:2023-11-30 16:15:45 25 4
gpt4 key购买 nike

我正在尝试获取文本文件中某一行的地址。该行包含以下内容;

凯马特,7055 东百老汇,图森亚利桑那州

我正在使用 strcpy 和 strtok 函数来提取地址(7055 East Broadway),但到目前为止我只能使用我的代码提取商店名称(Kmart)。

char strLine[] 从文件中获取行,我想将其返回到 char strAddress[]

我如何提取地址以及可能的城市和州?

#define MAX_CHARS_PER_LINE 80

void getAddress(char strAddress[], const char strLine[])
{

char newLine[MAX_CHARS_PER_LINE+1];

strcpy(newLine,strLine);
char* token = strtok(newLine, ",");

strAddress = token;

printf("%s\n",strAddress);


}

最佳答案

假设,

  1. 地址是该行中的第二个元素
  2. 以逗号分隔。

您可以使用strtok获取如下地址。

void getAddress(char strAddress[], const char strLine[])
{
char newLine[MAX_CHARS_PER_LINE+1];

strcpy(newLine,strLine);

char* token = strtok(newLine, ",");
if (token != NULL)
{
token = strtok(NULL, ",");
}
if (token != NULL)
{
strcpy (strAddress,token);
}
return;
}

要获取城市和州,只需再调用一次 token = strtok(NULL, ",");

What if I wanted to separate the city-state and just get the city and get the state separately?

这是一项更复杂的工作,因为城市和州之间没有逗号。您还需要注意城市可以有两个词的情况,例如新奥尔良。

您可以假设该状态有 2 个字符。在这种情况下,建议的路线是

  1. 在字符串中隔离城市 + 州
  2. 删除字符串末尾的空格
  3. 字符串的最后 2 个字符是状态。

关于c - 如何从文本行获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56982412/

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