字符串分割

题目描述

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

输入描述:

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

输出描述:

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

输入例子:
abc
123456789
输出例子:
abc00000
12345678
90000000
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str1 = in.next();
        String str2 = in.next();
        
        task(str1);
        task(str2);
        in.close();
    }
    /**
     * 对字符个数不为8的整数倍的字符串添加0成为8的整数倍,再截取打印
     * @param str
     */
    private static void task(String str) {
        int l = str.length();
        StringBuffer sb = new StringBuffer(str);
        if(l % 8 > 0) {
            int n = 8 - l % 8;
            while(n > 0) {
                sb.append("0");
                n --;
            }
        }
        
        
        int i = l / 8 + 1;
        for(int j = 0; j < i; j++) {
            if(j * 8 + 8 <= sb.length()) {
                String s = sb.substring(j * 8, j * 8 + 8);  //sustring左闭右开
                System.out.println(s);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/zywu/p/5805542.html