chilliefiber
chilliefiber

Reputation: 651

Strtok outputting just a part of the string

#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;
}

This is the output:

eseumdesconhecidolheoferecerflores.issoeimpulse.cities
umd

I have no idea what is happening at all. What I want is for the output of strtok to be a pointer to "eseumdesconhecidolheoferecerflores.issoeimpulse"

Upvotes: 0

Views: 33

Answers (1)

paddy
paddy

Reputation: 63481

The delimiter argument to strtok is a string containing individual characters used to separate the string.

You specified delimiters ., c, i, t, e, and s.

So it's no surprise the output is umd for the first token, since it is surrounded by characters in your delimiter string.

If you want to find a whole string, you should use strstr instead.

For example:

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

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

Upvotes: 4

Related Questions