C++

How to Split Strings Using Delimiter in C++

Splitting a string using a delimiter is a common operation in programming, particularly when working with text data. A delimiter is a character or sequence of characters used to separate one section of a string from another. When a text is separated into smaller substrings using a delimiter, the delimiter or separator is predetermined. Many programming tasks, such as input data parsing, text tokenization, and string processing, use this technique. There are several string-splitting methods available in C++, each having pros and cons.

In this article, we will explore some of the common ways to split a string using a delimiter in C++.

Split Strings Using Delimiter in C++

In C++, there are multiple approaches to break a string using a delimiter, including:

1: Using the find() and substr() Functions

A string can be divided using the C++ functions find() and substr(). The first instance of a substring is located using the find() method. If there are no more occurrences, the remaining piece of the string will be returned after being placed into the vector. The substring beginning at the start of the text and terminating at the delimiter may then be extracted using the substr() function. We can go on doing this until all the substrings have been obtained.

Here is a C++ example of how to split a string using a delimiter:

#include <iostream>

#include <string>

int main() {

std::string str = "apple,banana,cherry";

std::string delimiter = ",";

size_t pos = 0;

std::string token;

  while ((pos = str.find(delimiter)) != std::string::npos) {

    token = str.substr(0, pos);

std::cout << token << std::endl;

str.erase(0, pos + delimiter.length());

  }

std::cout << str << std::endl;

return 0;

}

In the example above, a string named “str” and a delimiter named “delimiter” are defined. The substrings from “str” are then extracted using a while loop. The location of the delimiter is returned by the find() method, or std::string::npos if it cannot be located. The substring from the start of “str” up to the delimiter is extracted using “substr()” in this spot, and it is then printed to the console. The extracted substring and the delimiter are then taken out of “str” using the “erase()” function. Once there are no more delimiters in “str”, we repeat this operation. Afterward, we output the last substring “cherry” to the console.

Output

2: Using the strtok() Function

The strtok() function is another function in C++ that can effectively split the strings using a delimiter in any C++ program. It takes out two inputs; the string to be divided and the delimiter character. Here’s an implementation of strtok() function in C++:

#include <iostream>

#include <cstring>

using namespace std;

int main()

{

  char str[100];

cout << " Enter a string: " <<endl;

cin.getline(str, 100);

  char *ptr;

ptr = strtok(str, " , ");

cout << " \n Splitting the string: " << endl;

  while (ptr != NULL)

  {

cout << ptr << endl;

ptr = strtok (NULL, " , ");

  }

  return 0;

}

The strtok() function is used in the code above to break a user-supplied input string into tokens, using a comma and a space as delimiters. Then it publishes each token to the console on a separate line. This is accomplished by storing the input string in a char array, iterating over the tokens with a char pointer, and then dividing the string repeatedly until all tokens have been displayed.

Output

3: Using the stringstream Class

Using the <std::stringstream> class is another technique to split a string in C++. It is possible to enter and output formatted data, including strings, using this class. A string that is being handled as a stream can have substrings extracted from it using the getline() method. The getline() method will extract the substring up to the delimiter if we provide it the delimiter as a parameter.

Here is an illustration of how to split a string in C++ using the stringstream() function.

#include <iostream>

#include <string>

#include <sstream>

#include <vector>

int main() {

std::string input_string = "apple, banana, cherry";

std::vector<std::string> tokens;

std::stringstream ss(input_string);

std::string token;

  while (std::getline(ss, token, ',')) {

tokens.push_back(token);

  }

  for (auto t : tokens) {

std::cout << t << std::endl;

  }

  return 0;

}

In the code above, a delimiter character is used to divide an input string into tokens using <std::stringstream>. Prior to extracting each token from the <stringstream> using the delimiter, the program initializes an <stringstream> object with the input string. A vector of strings is then expanded by each token. The program then loops through the vector, printing each token to the console at the end.

Output

Text Description automatically generated

Conclusion

Splitting a string using a delimiter is an effective approach in C++ and there are several built-in functions in C++ that make it possible to split strings. These functions include find(), substr(), strtok() and stringstream class. The developers should consider the specific requirements of their application and choose the function that best works for them.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.