1. 程式人生 > >java String字串空格隔開

java String字串空格隔開

public class StringTest {

    public static void main(String[] args) {

        String str = "1234567890123";
        String stri = spaceAt4(str);
        System.out.println(stri);
        //結果:1234 5678 9012 3
    }

    public static String spaceAt4(String str) {

        StringBuilder sb = new StringBuilder();
        int length = str.length();
        for (int i = 0; i < length; i += 4) {
            if (length - i <= 8) {      //防止ArrayIndexOutOfBoundsException
                sb.append(str.substring(i, i + 4)).append(" ");
                sb.append(str.substring(i + 4));
                break;
            }
            sb.append(str.substring(i, i + 4)).append(" ");
        }

        return sb.toString();
    }

}