Skip to main content

Split String in C++ with delimiters


In order to split string in c++ we can use strtok().

A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning. Read More Here

#include <iostream.h>
#include <string.h>

int main(int argc, char** argv)
{
    // multiple delimiters can be provided
    char const delimiters[] = "/:";    

    // initial string to split   
    std::string sCFIString = "/6/2702!/4/6/6/122/1:3";    

    // this pointer will point to the next word after every 'strtok' call
    char *token = strtok(const_cast<char*>(sCFIString.c_str()), delimiters);    

    // if returned pointer is NULL, then there is no more words
    while (0 != token)
    {
        puts(token); // print the word
        token = strtok(NULL, delimiters); // move to the next one
    }

    return 0;
}

Output
6
2702!
4
6
6
122
1
3

Comments