In C++, strtok() splits a mutable C-string into tokens separated by delimiter characters.
Include <cstring>.
This guide shows the C library helper in a C++ .cpp program with std::cout. Prefer std::string for new text code; keep these APIs for C interop and interviews.
Syntax
First call passes the string; later calls pass nullptr.
C++
char* t = std::strtok(buf, ",");
while (t) {
t = std::strtok(nullptr, ",");
}
Call
What it does
std::strtok(str, delim)
First token; mutates str.
std::strtok(nullptr, delim)
Next token using saved state.
POSIX offers strtok_r for reentrancy. C++ code often uses streams or string find loops instead.
Library declarations
C++
char* strtok(char* str, const char* delim);
Parameters
Parameter
Description
str
Mutable buffer on the first call; nullptr afterward.
delim
Set of delimiter characters.
Return Value
Return Value
Description
char*
Pointer to the next token, or nullptr when done.
C++ Examples
Example 1 — Basic strtok()
Split on commas.
C++
#include <cstring>
#include <iostream>
int main() {
char buf[] = "a,b,c";
char* t = std::strtok(buf, ",");
while (t) {
std::cout << t << ' ';
t = std::strtok(nullptr, ",");
}
std::cout << '\\n';
return 0;
}
Output
a b c
How It Works
First call receives the mutable buffer.
Each later call passes nullptr.
Tokens print separated by spaces.
Example 2 — Several Delimiters
Split on comma or space.
C++
#include <cstring>
#include <iostream>
int main() {
char buf[] = "one, two";
char* t = std::strtok(buf, ", ");
std::cout << t << '\\n';
t = std::strtok(nullptr, ", ");
std::cout << t << '\\n';
return 0;
}