首页 > 解决方案 > 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"

标签: cstringstrtok

解决方案


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

您指定了分隔符., c, i, t, e, 和s.

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

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

例如:

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

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

推荐阅读