C ++:如何分割字符串成均匀的尺寸较小的字符串? [英] C++: How do I split a string into evenly-sized smaller strings?
问题描述
在C ++中,我怎么字符串分割成均匀的尺寸更小的字符串?
In C++, how do I split a string into evenly-sized smaller string?
例如,我有一个字符串012345678,并希望将其分成5小串,这应该返回我像01,23,45,67,8的东西。
For example, I have a string "012345678" and want it to split it into 5 smaller strings, and this should return me something like "01", "23", "45", "67", "8".
我有确定的较小的字符串长度的麻烦。在previous例如,原来的字符串大小9,我想把它分成5个较小的字符串,因此除了最后一个每个小字符串应该是长度为9/5 = 1,但最后一个会长度9 - 1 * 4 = 5,这是不能接受的
I'm having trouble of determining the length of the smaller strings. In the previous example, the original string is size 9, and I want to split it into 5 smaller string, so each smaller string except the last one should be length 9 / 5 = 1, but then the last one will be length 9 - 1* 4 = 5, which is unacceptable.
所以这个问题的正式定义:原始的字符串被分为n个子,并没有两个子应在长度大于1不同。
So the formal definition of this problem: the original string is split into EXACTLY n substrings, and no two of the substrings should differ by greater than 1 in length.
我的重点不是C ++语法或图书馆。它是如何设计一个算法,使返回的字符串可以是几乎相等的大小。
My focus is not on C++ syntax or library. It's how to design an algorithm so that the returned string can be nearly-equal in size.
推荐答案
要<一href="http://stackoverflow.com/questions/8084010/algorithm-for-subdividing-an-array-into-semi-equal-uniform-sub-arrays/8084403#8084403">divide N个项目成M部分的,具有长度在一个单元内,可以使用公式(N * I + N)/ M - (N * I)/ M
作为我
长度个部分,如下图所示。
To divide N items into M parts, with lengths within one unit, you can use formula (N*i+N)/M - (N*i)/M
as length of i
'th part, as illustrated below.
#include <string>
#include <iostream>
using namespace std;
int main() {
string text = "abcdefghijklmnopqrstuvwxyz";
int N = text.length();
for (int M=3; M<14; ++M) {
cout <<" length:"<< N <<" parts:"<< M << "\n";
int at, pre=0, i;
for (pre = i = 0; i < M; ++i) {
at = (N+N*i)/M;
cout << "part " << i << "\t" << pre << "\t" << at;
cout << "\t" << text.substr(pre, at-pre) << "\n";
pre = at;
}
}
return 0;
}
例如,当 M
是4或5,code以上生产:
For example, when M
is 4 or 5, the code above produces:
length:26 parts:4
part 0 0 6 abcdef
part 1 6 13 ghijklm
part 2 13 19 nopqrs
part 3 19 26 tuvwxyz
length:26 parts:5
part 0 0 5 abcde
part 1 5 10 fghij
part 2 10 15 klmno
part 3 15 20 pqrst
part 4 20 26 uvwxyz
这篇关于C ++:如何分割字符串成均匀的尺寸较小的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!