Skip to content

Instantly share code, notes, and snippets.

@efeciftci
Last active October 25, 2021 04:28
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save efeciftci/9120921 to your computer and use it in GitHub Desktop.
Save efeciftci/9120921 to your computer and use it in GitHub Desktop.
An example that shows usage of strtok function in C programming language.
/*
* The following description is from Linux Programmer's Manual (strtok(3)):
*
* #include <string.h>
* char *strtok(char *str, const char *delim);
*
* The strtok() function breaks a string into a sequence of zero or more
* nonempty tokens. On the first call to strtok() the string to be parsed
* should be specified in str. In each subsequent call that should parse
* the same string, str must be NULL.
*
* The delim argument specifies a set of bytes that delimit the tokens in
* the parsed string. The caller may specify different strings in delim
* in successive calls that parse the same string.
*
* Each call to strtok() returns a pointer to a null-terminated string
* containing the next token. This string does not include the delimiting
* byte. If no more tokens are found, strtok() returns NULL.
*/
#include <stdio.h>
#include <string.h>
int main()
{
char message[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
char* word;
/* get the first word from the message, seperated by
* space character */
word = strtok(message, " ");
printf("1st word: %s\n", word);
/* get the second word from the message, NULL must be
* used to get tokens from the previous string now */
word = strtok(NULL, " ");
printf("2nd word: %s\n", word);
/* the following loop gets the rest of the words until the
* end of the message */
while ((word = strtok(NULL, " ")) != NULL)
printf("Next: %s\n", word);
return 0;
}
@StefanoBelli
Copy link

Useful, thanks

@robotenique
Copy link

noice

@labati
Copy link

labati commented Nov 2, 2016

thanks

@andoresu47
Copy link

Illustrative. Thanks!

@Lamia-Mihoubi
Copy link

why do we need to extract the second word seperately and what if the string contains only one word??

@HarryPease
Copy link

TYVM!

@v1b3m
Copy link

v1b3m commented Jun 27, 2018

Thanks for this, really useful.

@ayoueeb
Copy link

ayoueeb commented Apr 21, 2019

Thank you so much

@Ashis-007
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment