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

查看:207
本文介绍了将字符串分成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".

能请你帮我吗?

推荐答案

您可以递归进行.

零件尺寸m = (str_size+N-1)/N;
然后str_size -= m;N--;

First part size m = (str_size+N-1)/N;
Then str_size -= m; and 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天全站免登陆