Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is wcstok() in C?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

wcstok() is a built-in function defined in the <wchar.h> header.

The following is the function prototype:

wchar_t* wcstok (wchar_t* str, const wchar_t* delim, wchar_t ** ptr);

Functionality

We use wcstok() to split the input wide character string into tokens based on the characters in the delim string.

The wcstok() function for a space delimited string

Parameters and return

The function takes the following as input arguments:

  • str: pointer to a null-terminated wide character string

  • delim: pointer to the delimiter(s) string

  • ptr: pointer to an object of type wchar_t* that stores the next token

wcstok() returns the pointer to the next token.

If no token is found, the function returns NULL.

Code

#include <wchar.h>
#include <stdio.h>
#include <stddef.h>
int main(){
//Declaring wide char str
wchar_t str[] = L"Alice, Bob and Carl are good friends";
//ptr for tokens
wchar_t* ptr;
//Declaring delimiter string " ,"
wchar_t delim[] = L" ,";
//retrieve the first token
wchar_t* token = wcstok(str, delim, &ptr);
//loop to retrieve all tokens
while(token){
//print token
wprintf(L"%S\n", token);
//update token
token = wcstok(NULL, delim, &ptr);
}
return 0;
}

In the above example, we begin by declaring a wide character string.

We initialize the delimiter string to contain a space and a comma.

Next, we retrieve the first token through an explicit call to the wcstok() function.

Until we obtain a null pointer, the function updates the token to point to the beginning of the next token.

We pass NULL when updating the token. This is because the string has already been tokenized. Further calls to wcstok() update ptr to the next token until we encounter NULL.

RELATED TAGS

c

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring