Horje
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="geeks,for,geeks"

Output:
String after splitting:
geeks
for
geeks

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 = "geeks,for,geeks";
  
    // 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: 
geeks
for
geeks

Time Complexity: O(n)
Space Complexity: O(n)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Find the Product of 2D Array Elements in C++? How to Find the Product of 2D Array Elements in C++?
How to Convert a std::string to char* in C++? How to Convert a std::string to char* in C++?
How to Find the Median of Vector Elements in C++? How to Find the Median of Vector Elements in C++?
How to Find the Variance of Numbers in 2D Array in C++? How to Find the Variance of Numbers in 2D Array in C++?
How to Insert Elements from Vectors to a Map in C++? How to Insert Elements from Vectors to a Map in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17