STRTOK()

this function tokenizes (breaks down) a string into smaller, meaningful units (tokens) based on a delimiter. this can be used for breaking sentences into words, a CSV into individual items, or a command string into arguments.

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];  // Buffer to store user input (up to 99 characters + 1 for '\0')

    // Prompt user to enter a sentence (optional)
    // printf("Enter a sentence: ");

    // Read a full line of input from the user, including spaces
    // fgets() reads up to sizeof(str) - 1 characters or until a newline is found
    // It automatically adds '\0' at the end of the string
    fgets(str, sizeof(str), stdin);  

    // Delimiter character used to split words (space in this case)
    char delimiter[] = " ";

    // Pointer to hold each extracted word (token)
    char *token = strtok(str, delimiter);

    // Loop to extract and print all tokens
    while (token != NULL) {
        printf("Word: %s\n", token);          // Print the current word
        token = strtok(NULL, delimiter);      // Move to the next word
    }

    return 0;
}

 * thr strtok() tokenizes the string {entered by the user} based on space characters " "
    - it only prints the first token (word) before the first space character if NOT
      applied to a loop.
    - the strtok function with a NULL pointer as the first argument resumes from where 
      it left off in the previous call, so it doesn't tokenize the entire string in 
      one go.
#include <stdio.h>
#include <string.h>

int main() 
{
  char stringVariable[] = "Firstname Lastname!";
  char delimiter[] = " ";
  char *token = strtok(stringVariable, delimiter);
	
  while(token != NULL){
    printf("%s\n", token);
    token = strtok(NULL, delimiter);
  }
  return 0;
}

Last updated