-2

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;
}
Auron
  • 51
  • 5

2 Answers2

0

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;
}
Damien
  • 4,809
  • 4
  • 15
  • 20
-1

Given L is the length of the text, you can extract the first L%N parts with length l = L/N + 1 and the rest N - L%N parts with length l = L/N.

std::size_t N = 3;
std::string str = "some random stringxx";

std::vector<std::string> splits(N);
for (std::size_t i = 0, L = str.size(); i < N; ++i) {
    splits[i] = str.substr(i*(L/N) + std::min(i, L%N), L/N + (i < L%N ? 1 : 0));
}

Output:
  - 'some ra'
  - 'ndom st'
  - 'ringxx' 

Demo

Georgi Gerganov
  • 1,006
  • 9
  • 17