thegoat
thegoat

Reputation: 1

How to access a specific element of an index in the token returned from strtok

int index = 0;
for (char *tp = strtok(strings, " "); tp != NULL; tp = strtok(NULL, " \t\n")){
}

Let's say strings[] is something like "Today is nice," the first token return would be "Today" right? But doesn't strtok() return a pointer?

So if I want to loop through the word "Today" to print each letter out, how would I do that? Could I just do tp[index]?

Upvotes: 0

Views: 77

Answers (2)

gulpr
gulpr

Reputation: 4608

But doesn't strtok() return a pointer?

It returns a pointer which references the first character of the C string. C string is an array of characters with null terminating character at the end.

So if I want to loop through the word "Today" to print each letter out, how would I do that? Could I just do tp[index]?

Yes, it is the correct way. It is the same as *(tp + index). You can use both forms.

To print all characters (except null terminating character) in the string:

for(size_t index = 0; tp[index]; index++)
    printf("Character at index %zu is '%c'\n", index, tp[index]);

Upvotes: 2

Jabberwocky
Jabberwocky

Reputation: 50882

You probably want this:

int main(void)
{
  char strings[] = "Today is nice";

  for (char* tp = strtok(strings, " "); tp != NULL; tp = strtok(NULL, " \t\n"))
  {
    printf("\"%s\" ", tp);
  }
}

Yes strtok() return a pointer. The first call to strtok(somestring, ...) returns the pointer to the first substring, and the following calls to strtok(NULL, ... return the next substrings.

If you want to do it the hard way (the way you suggested) you can do this:

  for (char* tp = strtok(strings, " "); tp != NULL; tp = strtok(NULL, " \t\n"))
  {
    char ch;
    for (int i = 0; ch = tp[i]; i++)
      printf("%c", ch);

    printf(" ");
  }

I suggest you read again the chapter dealing with strings in your C learning material.

Upvotes: 2

Related Questions