前面的子串正常截取,最后一个子串判断从哪里开始填充0
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); do{ //读入数据 String s = in.nextLine(); int len = s.length(); //计算子串数量 int n; n = len%8 == 0 ? len/8 : len/8+1; String[] strings = new String[n]; //对于前面的子串,正常截取 StringBuilder builder; for(int i=0; i < n-1; i++){ builder = new StringBuilder(); for(int j=0; j < 8; j++){ builder.append(s.charAt(i*8+j)); } strings[i] = builder.toString(); } //对于最后一个子串,先填入字符串最后几个字母 builder = new StringBuilder(); for(int i=8*(n-1); i < len; i++){ builder.append(s.charAt(i)); } //若没填满8个,填充0 if(len%8 != 0){ for(int i=len%8; i < 8; i++) builder.append('0'); } strings[n-1] = builder.toString(); //输出 for(String t : strings) System.out.println(t); }while(in.hasNextLine()); } }