tawhidmonowar's blog

By tawhidmonowar, history, 5 weeks ago, In English

In C++, splitting a string by a delimiter is a common task, especially when parsing user input or working with formatted data. One of the simplest methods to achieve this is by using the strtok() function from the C standard library.

Let's walk through how you can split a string using multiple delimiters, such as commas and semicolons, with an example.

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    string str;
    cin >> str;

    char str_chr[str.length() + 1];
    strcpy(str_chr, str.c_str());

    char *token = strtok(str_chr, ",;");  // Splitting using ',' and ';'

    while (token != NULL) {
        cout << token << endl;
        token = strtok(NULL, ",;");
    }

    return 0;
}

Explanation:

  1. Convert to C-style String: The strtok() function works with C-style strings (character arrays), so we need to convert the C++ string (std::string) to a character array, it can be done using strcpy().

  2. The strtok() function takes two parameters: the string to split and a string of delimiter characters (in this case, "," and ";"). The function splits the string at every occurrence of any of the delimiters.

  3. The while loop continues extracting tokens until strtok() returns NULL, indicating that there are no more tokens left to extract.

Example Input/Output:

Input:
apple,banana;cherry
Output:
apple
banana
cherry

Time Complexity: O(n)

  • Vote: I like it
  • 0
  • Vote: I do not like it