题目描述
•连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
实现方法1:
#include<iostream>
#include<string>
using namespace std;
int main() {
string str;
int count = 0;
int remain_num = 0;
while (cin >> str) {
count = str.size() / 8;
remain_num = str.size() % 8;
for (int i = 0; i < count; i++) {
string full,temp;
for (int j = 0; j < 8; j++) {
temp = str[j];
full += temp;
}
cout << full << endl;
str.erase(str.begin(), str.begin() + 8);
}
if(remain_num){
string remain(8-remain_num, '0');
str += remain;
cout << str << endl;
}
}
}
实现方法2:
使用str.size()方法可以轻松的实现在一段字符串中提取部分内容
使用str.append()方法可以轻松实现拓展字符串
#include<iostream>
#include<string>
using namespace std;
int main() {
string str;
while (cin >> str) {
int remain_num = str.size() % 8;
while (str.size() >= 8) {
cout << str.substr(0, 8) << endl;
str = str.substr(8);//注意此处代表提取,从str[8]开始到str结尾的内容
}
if (remain_num) {
str.append(8 - remain_num, '0');
cout << str << endl;
}
}
}