MaximV
MaximV

Reputation: 325

how do you split a string embedded in a delimiter in C++?

I understand how to split a string by a string by a delimiter in C++, but how do you split a string embedded in a delimiter, e.g. try and split ”~!hello~! random junk... ~!world~!” by the string ”~!” into an array of [“hello”, “ random junk...”, “world”]? are there any C++ standard library functions for this or if not any algorithm which could achieve this?

Upvotes: 0

Views: 301

Answers (1)

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5786

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

vector<string> split(string s,string delimiter){
    vector<string> res;
    s+=delimiter;       //adding delimiter at end of string
    string word;
    int pos = s.find(delimiter);
    while (pos != string::npos) {
        word = s.substr(0, pos);                // The Word that comes before the delimiter
        res.push_back(word);                    // Push the Word to our Final vector
        s.erase(0, pos + delimiter.length());   // Delete the Delimiter and repeat till end of String to find all words
        pos = s.find(delimiter);                // Update pos to hold position of next Delimiter in our String 
    }   
    res.push_back(s);                          //push the last word that comes after the delimiter
    return res;
}

int main() {
        string s="~!hello~!random junk... ~!world~!";
        vector<string>words = split(s,"~!");
        int n=words.size();
        for(int i=0;i<n;i++)
            std::cout<<words[i]<<std::endl;
        return 0;
 }

The above program will find all the words that occur before, in between and after the delimiter that you specify. With minor changes to the function, you can make the function suit your need ( like for example if you don't need to find the word that occurs before the first delimiter or last delimiter) .

But for your need, the given function does the word splitting in the right way according to the delimiter you provide.

I hope this solves your question !

Upvotes: 2

Related Questions