- strtok function in c programming will help you to give the token of given input.
- This kind of function (strtok in c ) is very useful which reduce the length of c program.
strtok |
Use of the strtok function in c
strtok is an inbuilt function which is part of the <string.h> c header file.
Let's see first : -
#include<string.h>
char* strtok(char* str, const char* delim);
- This function take an input str and also a delimiter character delim.
- Then strtok() in c split the input string into the tokens which is based on the delimited character.
Return Value of strtok in c
- This function return a single string.
- strtok() in c call this function continuously until we get NULL input sting.
Example for strtok in c
#include<stdio.h>
#include<string.h>
int main() { // Our input string char input_string[] = "Hello from function in c!"; // Our output token list char token_list[20][20]; // We call strtok(input, delim) to get our first token // Notice the double quotes on delim! It is still a char* single character string! char* token = strtok(input_string, " "); int num_tokens = 0; // Index to token list. We will append to the list while (token != NULL) { // Keep getting tokens until we receive NULL from strtok() strcpy(token_list[num_tokens], token); // Copy to token list num_tokens++; token = strtok(NULL, " "); // Get the next token. Notice that input=NULL now! } // Print the list of tokens printf("Token List:\n"); for (int i=0; i < num_tokens; i++) { printf("%s\n", token_list[i]); } return 0; }
We use the strtok(NULL, " ") function in c and use the loop for until the get NULL.
Output strtok in c
Token List: Hello from Function in c