华为机试题--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;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章