描述
•输入一个字符串,请按长度为8拆分每个输入字符串并进行输出;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
输入描述:
连续输入字符串(每个字符串长度小于等于100)
输出描述:
依次输出所有分割后的长度为8的新字符串
示例
输入:
abc
输出:
abc00000
思路
- 此类等长分割不尽问题,最常用的思路就是就除数和余数。
代码
errcode.h
#pragma once
enum {
ERRCODE_NO_ERR = 0,
ERRCODE_INVALID_ARGUMENT = 1,
};
StringSpliter.h
#pragma once
#include <memory>
using namespace std;
class StringSpliter
{
public:
virtual void input() = 0;
virtual void process() = 0;
virtual void output() = 0;
public:
static shared_ptr<StringSpliter> create();
};
StringSpliterImpl.h
#pragma once
#include <string>
#include <vector>
#include "StringSpliter.h"
class StringSpliterImpl : public StringSpliter
{
public:
void input() override;
void process() override;
void output() override;
private:
uint8_t verifyValidity();
public:
StringSpliterImpl();
~StringSpliterImpl();
private:
string userString;
vector<string> strings;
uint8_t errcode;
};
StringSpliter.cpp
#include "StringSpliterImpl.h"
shared_ptr<StringSpliter> StringSpliter::create()
{
return dynamic_pointer_cast<StringSpliter>(make_shared<StringSpliterImpl>());
}
StringSpliterImpl.cpp
#include <iostream>
#include "StringSpliterImpl.h"
#include "errcode.h"
void StringSpliterImpl::input()
{
getline(cin, userString);
}
void StringSpliterImpl::process()
{
errcode = verifyValidity();
if (ERRCODE_NO_ERR != errcode) {
return;
}
auto previousSplitePos = 0;
auto times = userString.size()/8;
while (times--) {
strings.push_back(userString.substr(previousSplitePos, 8));
previousSplitePos += 8;
}
auto sizeOfLastSegment = userString.size()%8;
if (sizeOfLastSegment > 0) {
string lastSegment = userString.substr(previousSplitePos);
while (8 - sizeOfLastSegment++) {
lastSegment += '0';
}
strings.push_back(lastSegment);
}
}
void StringSpliterImpl::output()
{
for (auto& ele:strings) {
cout << ele << '\n';
}
cout << endl;
}
uint8_t StringSpliterImpl::verifyValidity()
{
if (0 == userString.size()) {
return ERRCODE_INVALID_ARGUMENT;
}
return ERRCODE_NO_ERR;
}
StringSpliterImpl::StringSpliterImpl()
:errcode(ERRCODE_NO_ERR)
{
}
StringSpliterImpl::~StringSpliterImpl()
{
}
main.cpp
#include "StringSpliter.h"
int main(int atgc, char** argv)
{
auto spliter = StringSpliter::create();
spliter->input();
spliter->process();
spliter->output();
return 0;
}