Strtok仅输出字符串的一部分

时间:2018-11-15 00:58:33

标签: c string strtok

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

int main(){
  char name[] = "eseumdesconhecidolheoferecerflores.issoeimpulse.cities";
  char *str;
  printf("%s\n", name)
  str = strtok(name, ".cities");
  printf("%s\n", str);
  return 0;
}

这是输出:

eseumdesconhecidolheoferecerflores.issoeimpulse.cities
umd

我完全不知道发生了什么。我想要的是strtok的输出是指向"eseumdesconhecidolheoferecerflores.issoeimpulse"

的指针

1 个答案:

答案 0 :(得分:4)

strtok的定界符参数是一个字符串,其中包含用于分隔字符串的各个字符。

您指定了定界符.cites

因此,第一个标记的输出为umd也就不足为奇了,因为它被定界符字符串中的字符包围。

如果要查找整个字符串,则应改用strstr

例如:

char name[] = "eseumdesconhecidolheoferecerflores.issoeimpulse.cities";
char *pos;

pos = strstr(name, ".cities");
if (pos)
{
    *pos = '\0';
    printf("%s\n", name);
}