Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,880 questions

51,806 answers

573 users

How to split a string by substring delimiter in C++

2 Answers

0 votes
#include <iostream>
#include <vector>

std::vector<std::string> split_by_substring(const std::string& str, const std::string& delimiter) {
    std::vector<std::string> tokens;
    size_t start = 0, end = 0;
    
    while ((end = str.find(delimiter, start)) != std::string::npos) {
        tokens.push_back(str.substr(start, end - start));
        start = end + delimiter.length();
    }
    tokens.push_back(str.substr(start));
    
    return tokens;
}

int main() {
    std::string str = "C++ programming language and computer programs and game development";
    std::string delimiter = "and";
    
    std::vector<std::string> result = split_by_substring(str, delimiter);
    
    for (const auto& s : result) {
        std::cout << s << std::endl;
    }
}



/*
run:

C++ programming language 
 computer programs 
 game development

*/

 



answered Jan 18, 2025 by avibootz
0 votes
#include <iostream>
#include <regex>
#include <vector>

std::vector<std::string> splitString(const std::string& str, const std::string& delimiter) {
    std::vector<std::string> tokens;
    std::regex re(delimiter);
    std::sregex_token_iterator it(str.begin(), str.end(), re, -1);
    std::sregex_token_iterator reg_end;
    
    for (; it != reg_end; ++it) {
        tokens.push_back(it->str());
    }
    
    return tokens;
}

int main() {
    std::string str = "C++ programming language and computer programs and game development";
    std::string delimiter = "and";
    
    std::vector<std::string> result = splitString(str, delimiter);
    
    for (const auto& s : result) {
        std::cout << s << std::endl;
    }
}


/*
run:

C++ programming language 
 computer programs 
 game development

*/

 



answered Jan 18, 2025 by avibootz

Related questions

3 answers 101 views
1 answer 67 views
1 answer 40 views
1 answer 91 views
...