Code explanation
Line 1–2: Include the necessary libraries: iostream
for output and cstring
for string manipulation (strtok
).
Line 4: Define the tokenizeString
function, which takes a string and a delimiter for tokenizing the input string.
Line 5: Declare a character array tempStr
to store a mutable copy of the input string.
Line 6: Copy the content of the input string str
into tempStr
using std::strcpy
.
Line 8: Tokenize tempStr
using std::strtok
and the provided delimiter. The first token is returned and stored in token
.
Line 9–12: Loop through the tokens while token
is not null. Print each token to the console. Inside the loop, get the next token by calling std::strtok
again with nullptr
and the same delimiter.
Line 16–17: Start the main
function, define the input string, and set delimiters to comma and space.
Line 21: Call tokenizeString
to tokenize the input string and print the tokens.
Modify the above code to handle multiple delimiters, such as a comma (,
), semicolon (;
), and space (
). Make sure no empty tokens are printed.