字符串分割

题目描述

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

输入描述:

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

输出描述:

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

示例1

输入

abc
123456789

输出

abc00000
12345678
90000000

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<iomanip>
using namespace std;

int main() {

    string input;
    while (cin >> input) {
        if (input.size() <= 8) {
            cout << left << setw(8) << setfill('0') << input << endl;
            continue;
        }
        else {
            int diff = (8 - input.size() % 8) % 8;
            input.insert(input.size(), diff, '0');
            for (int i = 0; i < input.size() / 8; i++) {
                cout << string(input,i*8,8) << endl;
            }
        }
    }
    return 0;
}

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {

    char input[101] = { 0 };
    while (scanf("%s", input) != EOF) {
        int sz = strlen(input);
        if (sz <= 8) {
            printf("%s", input);
            for (int i = 0; i < 8 - sz; i++) {
                printf("%c", '0');
            }
            printf("\n");
        }
        else {
            int diff = (8 - sz % 8) % 8;
            for (int i = 0; i < sz; i++) {
                printf("%c", input[i]);
                if ((i+1) % 8 == 0 && i != 0) {
                    printf("\n");
                }
            }
            for (int i = 0; i < diff; i++) {
                printf("%c", '0');
            }
            if(diff!=0)printf("\n");
        }
    }
    return 0;
}
This entry was posted in hwleetcode. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.