How to write an equivalent to PHP explode(string $separator, string $string, int $limit = INT_MAX): array in C++

1 Answer

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

std::vector<std::string> explode(const std::string& separator, const std::string& input, int limit = INT32_MAX) {
    std::vector<std::string> result;
    size_t start = 0;
    size_t end;
    int splits = 0;

    while ((end = input.find(separator, start)) != std::string::npos && splits < limit - 1) {
        result.push_back(input.substr(start, end - start));
        start = end + separator.length();
        splits++;
    }

    // Add the remaining part
    result.push_back(input.substr(start));
    
    return result;
}


int main() {
    std::string text = "c++,c,python,php,java";
    std::string delimiter = ",";
    int limit = 3;

    std::vector<std::string> parts = explode(delimiter, text, limit);

    for (const auto& part : parts) {
        std::cout << part << std::endl;
    }
}



/*
run:

c++
c
python,php,java

*/

 



answered Nov 19, 2025 by avibootz

Related questions

...