1- Description
连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。输入描述:
连续输入字符串(输入2次,每个字符串长度小于100)
输出描述:
输出到长度为8的新字符串数组示例1:
输入:
abc
123456789
输出:
abc00000
12345678
90000000
2- Solution
#include <iostream>
#include <string>
using namespace std;
int main(){
string str1;
string str2;
while(cin >> str1){
int str1quot = str1.length() / 8;//商Quotient
int str1remd = str1.length() % 8;//余数remainder
for(int i = 0; i < str1quot * 8; ++i){
cout << str1[i];//针对含有8个元素的子串,直接输出
if((i + 1) % 8 == 0){
cout << endl;//换行
}
}
if(str1remd != 0){
for(int j = 0; j < str1remd; ++j){//输出不足八位的部分
cout << str1[str1quot * 8 + j];
}
for(int k = 0; k < 8 - str1remd; ++k){//末尾补0
cout <<0;
}
cout << endl;//换行
}
while(cin >> str2){
//整理成函数会更好
int str2quot = str2.length() / 8;//Quotient and remainder
int str2remd = str2.length() % 8;//余数
for(int i = 0; i < str2quot * 8; ++i){
cout << str2[i];
if((i + 1) % 8 == 0){
cout << endl;//换行
}
}
if(str2remd != 0){
for(int j = 0; j < str2remd; ++j){
cout << str2[str2quot * 8 + j];
}
for(int k = 0; k < 8 - str2remd; ++k){
cout <<0;
}
cout << endl;//换行
}
}
}
return 0;
}
- C++ string 类中substr函数可以得到指定位置开始指定长度的子串,这样的解法更加简洁
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
while(getline(cin,str)){//每次得到一行
while(str.size()>8){
cout << str.substr(0,8) <<endl;//从str[0]开始,向后输出字符串长度为8的子字符串
str=str.substr(8);//从第str[8]开始截取新的字符串
}
cout << str.append(8-str.size(), '0') << endl; //不够8位的补0
}
}
欢迎关注公众号:CodeLab