Mastering strtok in C: How to Split Strings into Tokens (Step-by-Step)

Опубликовано: 25 Май 2026
на канале: Programming with Sikander
1,907
43

int main()
{
char name[30] = "Programming with Sikander";

char *ptr = strtok(name, " ");
while(ptr != NULL){
printf("ptr = %s %ld\n", ptr, strlen(ptr));
ptr = strtok(NULL, " ");
}
}

This tutorialr provides a deep dive into the strtok function in C. This powerful string tokenizer is essential for breaking a string into a sequence of zero or more non-empty records, known as tokens.
What you will learn in this session:
• The strtok Declaration: Understand the two arguments required—the source string and the delimiter (the character or sequence that separates your tokens).
• The "First Call" Rule: Learn why the first time you call strtok, you must pass the string variable, but in every subsequent call, you must pass NULL to continue parsing the same string.
• How it Works (Internal Logic): We reveal how strtok actually modifies your string by replacing every encountered delimiter with a null character (\0) and returning a pointer to the current word.
• Parsing Multiple Words: Discover how to use a while loop to automatically extract every word from a string (like "programming with sikander") until the function returns NULL.
• Practical Application: See a demonstration of how to process these tokens individually, such as calculating the length of each word using strlen.
This lecture is perfect for students and developers looking to understand string manipulation, preparation for CSV file parsing, or technical coding interviews.