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 129 views
1 answer 76 views
1 answer 62 views
1 answer 108 views
...