华为笔试题:字符串分割

题目描述

•连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
•长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。

输入描述:

连续输入字符串(输入2次,每个字符串长度小于100)

输出描述:

输出到长度为8的新字符串数组

示例1

输入

abc
123456789

输出

abc00000
12345678
90000000
#include <iostream>
#include <string>

using namespace std;

void func1(string s) {
    int len = s.length();
    cout << s;
    if (len < 8) {
        for (int i = 0; i < 8 - len; ++i) {
            cout << '0';
        }
    }
    cout << endl;
}

void func2(string s) {
    int len = s.length();
    int index = len % 8;

    for (int i = 0; i < len - index; ++i) {
        cout << s[i];
        if ((i + 1) % 8 == 0) cout << endl;
    }
    if(index != 0)
        func1(s.substr(len - index, len - 1));
}

int main() {
    string s;
    while (cin >> s) {
        if (s.size() <= 8) func1(s);
        else func2(s);
    }
    return 0;
}
发布了34 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41111088/article/details/104771205