【问题标题】:Strtok outputting just a part of the stringStrtok 仅输出字符串的一部分
【发布时间】:2018-11-15 00:58:33
【问题描述】:
#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"的指针

【问题讨论】:

  • 在回答显而易见的问题之前(这就是 strtok 的工作原理)read the documentation of the function,然后解释一下你期望输出应该是什么以及为什么你会这样想了解该功能的工作原理(假设您实际阅读了我链接的内容)
  • 如果你只是想剥离 .cities 那么不要使用 strtok,它的杀伤力太大了​​。

标签: c string strtok


【解决方案1】:

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

您指定了分隔符 .、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);
}

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多