How to Split a String by a Delimiter in C++?
In C++, a string stores a sequence of characters that represents some textual data. The delimiters are used to separate those sequences of characters in a string. This process is called splitting or tokenization. In this article, we will learn how to split a string by a delimiter in C++.
For Example,
Input:
str="Beginner,for,Beginner"
Output:
String after splitting:
Beginner
for
Beginner
Split String Using Delimiter in C++
To split a string using a delimiter, we can use std::getline
combined with std::stringstream
to extract all the tokens from the string
separated by a specified delimiter, and keep storing the token in a vector of string.
C++ Program to Split a String by a Delimiter
C++
// C++ Program to split a string by a delimiter #include <iostream> #include <sstream> #include <vector> using namespace std; int main() { // Input string string inputString = "Beginner,for,Beginner" ; // Create a stringstream object with the input string stringstream ss(inputString); // Tokenize the input string by comma delimiter string token; vector<string> tokens; char delimiter = ',' ; while (getline(ss, token, delimiter)) { tokens.push_back(token); } // Output the string after splitting cout << "String after splitting: " << endl; for ( const auto & part : tokens) { cout << part << endl; } return 0; } |
Output
String after splitting: Beginner for Beginner
Time Complexity: O(n)
Space Complexity: O(n)
Contact Us