[Solved] Split string into N parts [closed]


You can do it recursively.

First part size m = (str_size+N-1)/N;
Then str_size -= m; and N--;

A little example:

#include <iostream>
#include <vector>
#include <string>

std::vector<std::string> split_string(const std::string& s, int N) {
    std::vector<std::string> vect;
    if (N > s.size()) return vect;
    vect.resize(N);
    int n = s.size();
    auto it = s.begin();
    int Nnew = N;
    for (int i = 0; i < N; i++) {
        int m = (n+Nnew-1)/Nnew;
        vect[i] = std::string (it, it+m);
        it += m;
        n = n - m;
        Nnew--;
    }
    return vect;
}

int main() {
    int N = 3;
    std::string str = "Very!HappyXmas";
    auto result = split_string (str, N);
    for (auto s : result) {
        std::cout << s << "\n";
    }
    return 0;
}

0

solved Split string into N parts [closed]