Tokenizing a string denotes "splitting" a string with respect to a delimiter.
E.g:
str = "I love playing PC games!!"
tokenized string = "I" | "love" | "playing" | "PC" | "games!!"(delimiter = " ")
Ways of tokenizing a string in C++ :
- Using strtok() function:
strtok() function splits the string on the basis of delimiter passed to it by the user.
Template:
strtok(str,<delimiter>) : will return a char pointer to the first token of the string.
**NOTE:
For the second token onward, instead of str, we need to pass a "NULL"; so that we can get the next token from the string. We do so, because; the internal implementation of the strtok() function stores the last starting address of the string passed; and if we keep passing the same string again and again, it will return us back with the same token(1st token) of the string.
**NOTE:
If we would have not passed NULL(inside the loop: used for getting from second token onwards!!), the loop would have no termination as the "ptr" variable, would never have got a NULL value. : Hence the program converts to an infinite loop.
2. Using our own String tokenizing function:
Here mytok() is our tokenizer function; it takes in two parameters : (char *, char delim) and performs tokenization for us of the string with respect to the deliminator passed as the argument.
(*read comments in the code for better clarity of how things are working in there!!😊😊😊).
This was all about string tokenizer in C++. More information would be added later on this page in the future. Keep Coding, keep smiling!!😊
Comments
Post a Comment