将字符串拆分为 N 个部分 [英] Split string into N parts

查看:28
本文介绍了将字符串拆分为 N 个部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Arduino 代码,它输入一个可变大小的字符串,目的是将字符串分成 N 个部分(同样 N 由 Arduino 代码输入,它是一个变量).

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).

我发现不同的代码将字符串分成 N 个相等的部分,但如果字符串有 9 个字符并且需要的部分是 2,则代码不起作用.

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

不同于零.

例如,如果字符串是HELLO"部分为 2,输出应为HEL";和LO".

For example, if the string is "HELLO" and the parts is 2, the output should be "HEL" and "LO".

你能帮我吗?

正确答案

#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;
}

推荐答案

您可以递归进行.

第一部分尺寸m = (str_size+N-1)/N;
然后 str_size -= m;N--;

一个小例子:

#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;
}

这篇关于将字符串拆分为 N 个部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆