java 字符串长度分割不足位数补齐0

package com.patience.interview.huawei;

import java.util.Scanner;

/**
 * @author Green.Gee
 * @date 2022/7/5 16:26
 * @email [email protected]
 */
public class SplitString {

    static final int N = 8;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int len = str.length();
        if(len < N){
            String oneStr = appendZero(str,N);
            System.out.println(oneStr);
        }else{
            int index = 0;
            while(index < len){
                int checkIndex = index + N;
                int endIndex = 0;
                if(checkIndex > len){
                    endIndex = index + (len - index);
                }else{
                    endIndex = index + N;
                }
                String tempStr = str.substring(index,endIndex);
                String oneStr = appendZero(tempStr,N);
                System.out.println(oneStr);
                index += N;
            }
        }
    }
    // 字符串不足n长度后补0
    public static String appendZero(String str,int n){
        int c = n - str.length();
        String oneStr = str;
        if(c > 0){
            for(int i = 0;i < c; i++){
                oneStr += "0";
            }
        }
        return oneStr;
    }
}

你可能感兴趣的:(算法【,Hard,Code】,java,开发语言)