严正声明:本文系作者davidhopper原创,未经许可,不得转载。
题目描述
连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
输入描述:
连续输入字符串(输入2次,每个字符串长度小于100)
输出描述
输出到长度为8的新字符串数组
示例1
输入
abc
123456789
输出
abc00000
12345678
90000000
答案
#include <iostream>
#include <string>
#include <vector>
int main() {
const std::size_t FIXED_LEN = 8;
std::string line;
std::vector<std::string> words;
while (std::getline(std::cin, line)) {
if (line.empty())
continue;
std::size_t len = line.length();
std::size_t loop_num = len / FIXED_LEN;
for (std::size_t i = 0; i < loop_num; ++i) {
words.emplace_back(line.substr(i* FIXED_LEN, FIXED_LEN));
}
if (loop_num * FIXED_LEN < len) {
std::string last_word = line.substr(loop_num * FIXED_LEN);
std::size_t patched_zero_num = FIXED_LEN - len % FIXED_LEN;
while (patched_zero_num-- > 0) {
last_word += '0';
}
words.emplace_back(last_word);
}
}
for (const auto& str: words) {
std::cout << str << std::endl;
}
return 0;
}