0

我是 C 新手,我想了解如何仅使用 strchr() 从字符串中跟踪多个单词。不能使用 strtok、scanf 或类似函数。

我有字符串:

char myImput[51]="my flight to New Orleans, is at 12:30"

字符串格式为:“我的航班城市名,位于 hh:mm” 我想提取城市名(可以有空格)hh 和 mm

有没有办法将城市名称添加到一个名为 city 的新字符串中,hh 到小时,分钟到分钟?

我想:

printf("the flight to %s, is at %s hr and %s mins", cityname, hour, minutes);

我真的很感谢你的帮助提前谢谢你

4

2 回答 2

0

如果你必须使用它,我有一个关于 strchr 的提议:

    const char myImput[51]="my flight to New Orleans, is at 12:30";
    const char ch = ' ';//ch is the delimiter'an unsigned char)
    char *rst;//the string result after the first occurence of ch
    rst=strchr(myImput,ch) ;
     printf("String after |%c| is - |%s|\n", ch, rst) ;

     while(rst !=NULL)
     {
     printf("String after |%c| is - |%s|\n", ch, rst) ;
     rst=rst+1 ;
     rst = strchr(rst, ch);
     }

PS:我增加 rstrst = rst + 1因为 strchr 返回第一次出现的分隔符结果,例如,它返回“飞往新奥尔良的航班,在 12:30”,字符串的第一个有空格,导致无限循环因为它总是找到第一个出现的地方就是那个空间!我希望你理解我!现在轮到你做同样的事情了。

于 2020-04-06T15:49:33.793 回答
0

在 C 中,strtok() 函数用于根据特定的分隔符将字符串拆分为一系列标记。这是语法: char *strtok(char *str, const char *delim) 所以你可以像这样简单地做:

 char myImput[51]="my flight to New Orleans, is at 12:30";
 // Extract the first token
 char * token = strtok(myImput, " ");
 // loop through the string to extract all other tokens
  while(token != NULL ) {
  printf( " %s\n", token ); //printing each token
  token = strtok(NULL, " ");
  }

现在您可以对时间标记(在您的情况下是最后一个标记)执行相同的操作。有关更多信息,请查看此链接

于 2020-04-06T00:37:19.033 回答