use of strtok
The strtok
function in C++ is used to split a string into a sequence of tokens based on a delimiter character. Here is an explanation of each step involved in using strtok
:
Include the necessary header file:
cpp #include <cstring>
Declare a character array to store the input string:
cpp char inputString[] = "Hello, world! This is a sample string.";
Declare a character pointer to store the first token:
cpp char *token;
Use
strtok
to get the first token:cpp token = strtok(inputString, " ");
The first argument of
strtok
is the input string to be tokenized. In this case, it isinputString
.The second argument of
strtok
is the delimiter character. In this case, it is a space character (" "
).Continue using
strtok
to get subsequent tokens: ```cpp while (token != NULL) { // Process the token // ...// Get the next token token = strtok(NULL, " "); } ```
The first argument of
strtok
is set toNULL
in subsequent calls to continue tokenizing the original string.The second argument of
strtok
is the same delimiter character used in the first call.Process each token as needed: ```cpp while (token != NULL) { // Process the token std::cout << "Token: " << token << std::endl;
// Get the next token token = strtok(NULL, " "); } ```
In this example, the token is simply printed to the console.
- Remember to include the
<iostream>
header file for usingstd::cout
to print the tokens:cpp #include <iostream>
That's it! This is a basic explanation of using strtok
in C++ to tokenize a string.