【HJ4】字串分隔
阿新 • • 發佈:2020-12-31
題目描述
連續輸入字串,請按長度為8拆分每個字串後輸出到新的字串陣列;
長度不是8整數倍的字串請在後面補數字0,空字串不處理。
輸入描述:
連續輸入字串(輸入多次,每個字串長度小於100)
輸出描述:
輸出到長度為8的新字串陣列
示例1
輸入
abc
123456789
輸出
abc00000
12345678
90000000
題解思路
- 暴力求解:使用一個 8 字元長度的快取陣列,依次存放目標字元,滿 8 個字元就輸出;不滿 8 個字元則判斷是否需要末尾寫入 0(即判斷快取陣列中是否存入字元)
- 利用 C++ string 的 substr 分割函式
程式碼實現
#include <iostream>
#include <cstring>
int main()
{
using namespace std;
char str[101] = {0};
char temp[9] = {0};
while(cin.getline(str, 101)) {
int len = strlen(str);
int k = 0;
for(int i = 0; i < len; ++i) {
temp[k++] = str[i];
if(k == 8) {
cout << temp << endl;
k = 0;
}
}
if(k != 0) {
while(k < 8) {
temp[k++] = '0';
}
cout << temp << endl;
}
}
return 0;
}
使用 C++ string 的程式碼實現:
#include <iostream>
#include <string>
int main()
{
using namespace std;
string str;
while(cin >> str) {
while(str.size() >= 8) {
cout << str.substr(0, 8) << endl;
str = str.substr(8);
}
if(str.size() > 0) {
str += "00000000";
cout << str.substr(0, 8) << endl;
}
}
return 0;
}