華爲機試題--4.字符串分隔

題目描述

•連續輸入字符串,請按長度爲8拆分每個字符串後輸出到新的字符串數組;
•長度不是8整數倍的字符串請在後面補數字0,空字符串不處理。

輸入描述:
連續輸入字符串(輸入2次,每個字符串長度小於100)

輸出描述:
輸出到長度爲8的新字符串數組

輸入例子:
abc
123456789

輸出例子:
abc00000
12345678
90000000

注意幾個邊界情況的判定
ss.substr(pos,n) 從原始stringpos開始取n個字符返回給新的string

#include <iostream>
#include <sstream>

using namespace std;
void cutString(string &str);

int main()
{
    string str;
    while (getline(cin, str))
    {
        cutString(str);
    }
    return 0;
}

void cutString(string &str){
    int len = str.size();

    if (len < 8){
        str.insert(str.end(), 8 - len, '0');
        cout << str << endl;
    }
    else
    {
        int count = 0;
        while (len / 8 != 0)
        {
            string tmp = str.substr(0 + count, 8);
            cout << tmp << endl;
            len -= 8;
            count += 8;
        }
        if (len>0){
            string tmp = str.substr(count, str.size());
            tmp.insert(tmp.end(), 8 - len, '0');
            cout << tmp << endl;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章