题解|HJ4 字符串分隔
字符串分隔
https://www.nowcoder.com/practice/d9162298cb5a437aad722fccccaae8a7?tpId=37&&tqId=21227&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking
连续输入字符串,请按长度为8拆分每个输入字符串并进行输出; 长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。 (注:本题有多组输入)
方法一:正常输入,暴力模拟
对字符串进行循环,每八位输出一次,如果最后一次不足八位,就在后面补0。
时间复杂度:,解释:遍历一遍字符串时间复杂度为。
空间复杂度:,解释:需要长度的数组存放字符串。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main() {
string str;
while(cin >> str){
int len = str.length();
string tmp = "";
int cnt = 0; //使用cnt维护到了当前需要输出序列的第几位
for(int i = 0; i < len; i++) {
//每8位输出一次换行
if(cnt == 8) {
cout << endl;
cnt = 0;
}
//直接输出每个字符
cout<<str[i];
cnt += 1;
}
//看剩余多少位需要补零
if(cnt < 8 && cnt != 0){
for(int j = 0; j < 8 - cnt; j++){
cout << "0";
}
}
printf("\n");
}
return 0;
}
方法二:以八位为单字符串长度进行输入,对不足八位的输入进行补0
在C/C++中,可以以scanf("%8s",str)以八位为切片长度进行输入,这种输入方法能够自动对字符串进行长度为的切分。如果当前输入的字符串切片不满八位,在后面补零。
时间复杂度:,解释:遍历一遍字符串时间复杂度为。
空间复杂度:,解释:需要长度的数组存放字符串。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char str[105];
while(scanf("%8s", str) != EOF) {
int len = strlen(str);
printf("%s", str);
for(int i = 0; i < 8 - len; i++){
putchar('0');
}
printf("\n");
}
}