本帖最后由 yuxijian2020 于 2021-5-8 09:41 编辑 #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
constexpr size_t MAX_LEN = 50;
struct Part
{
size_t start;
size_t len;
Part() : start(0), len(0) {}
Part(size_t s, size_t l) : start(s), len(l) {}
};
class StringSplitPlan
{
public:
StringSplitPlan() = delete;
explicit StringSplitPlan(StringSplitPlan& other) :
str(other.str), len(other.len), splits(other.splits) {}
explicit StringSplitPlan(StringSplitPlan&& other)
{
str = move(other.str);
len = other.len;
splits.swap(other.splits);
}
explicit StringSplitPlan(const string& str) : str(str), len(1) { this->Split(); }
explicit StringSplitPlan(const string &str, size_t len) : str(str), len(len) { this->Split(); }
const string& GetString() const { return str; }
size_t GetLen() const { return len; }
const vector<vector<Part>>& GetArray() const { return splits; }
void PrintAll() const
{
printf_s("Case %lld:\n", len);
for(const auto& vec : splits)
{
for(const auto& part : vec)
printf_s("%s ", string(str, part.start, part.len).c_str());
printf_s("\n");
}
}
private:
void Split()
{
for (size_t pos = 1; pos <= len; ++pos)
{
vector<Part> temp;
size_t start = 0, end = pos;
temp.emplace_back(Part(start, end - start));
do
{
start = end;
end += len;
temp.emplace_back(Part(start, end - start));
} while (end <= str.size());
splits.emplace_back(temp);
}
}
//待分割字符串
string str;
//每块长度
size_t len;
//分割后的下标数组
vector<vector<Part>> splits;
};
char* GetInputString()
{
char* temp = new char[MAX_LEN];
memset(temp, 0, MAX_LEN);
char c = 0;
int i = 0;
while((c = getchar()) != '\n')
temp[i++] = c;
if(temp[i - 1] == '\r')
temp[i - 1] = '\0';
return temp;
}
int main()
{
string str;
size_t len;
vector<StringSplitPlan> result;
char* c;
printf_s("请输入一个字符串:");
cin >> str;
getchar();
while(1)
{
printf_s("请输入分割后的子串的最大长度(直接回车则结束输入):");
c = GetInputString();
if(strlen(c) == 0)
break;
len = static_cast<size_t>(atoll(c));
delete[] c;
if(len > str.size())
{
printf_s("子串长度不能大于原字符串!\n");
continue;
}
result.emplace_back(StringSplitPlan(str, len));
}
for(const auto& i : result)
i.PrintAll();
return 0;
}
|