I am developing an Arduino code that take in input a string with variable size and the aim is to split the string into N parts (also N is taken in input by the Arduino code and it is a variable).
I found different code that split the string into N equal parts but in case the string has 9 character and the needed parts are 2, the code doesn't work.
My idea is to create a code that is able to split the string though the result of
str_size % n
is different than zero.
For example, if the string is "HELLO" and the parts is 2, the output should be "HEL" and "LO".
Could you please help me?
CORRECT ANSWER
#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;
}