Java String 后面加空格的几种方法

1.StringUtils

import org.apache.commons.lang3.StringUtils;

 

StringBuilder mBuffer1 = new StringBuilder("");

        mBuffer1.append(StringUtils.rightPad("测试", 10, "  ")

               +"  α"+StringUtils.rightPad("12", 10, " ")

                +",   β/γ"+StringUtils.rightPad("12.6", 10, " ")

                +"\r\n");

        System.out.print(mBuffer1);

2.String.format

StringBuilder mBuffer = new StringBuilder("");

        mBuffer.append(String.format("%-5s", "测试")

               +"  α"+String.format("%-10f",126f)

                +",   β/γ"+String.format("%-10f",12.6)

                +"\r\n");

        System.out.print(mBuffer);

 

 

鉴于上述2种方法都没有很好的达成目的,所以:

 

3.自己写

参考 https://www.cnblogs.com/whycxb/p/5063363.html

StringBuilder mBufferET = new StringBuilder("");

    mBufferET.append(addBlank("测试",10)+

                   "  α"+addBlankNum("126", 10)+

                    ",   β/γ"+addBlankNum("12.6",10)+"\r\n");

    mBufferET.append(addBlank("测试啊啊啊",10)+

                  "  α"+addBlankNum("128.99",10)+

                   ",   β/γ"+addBlankNum("12.6",10)+"\r\n");

System.out.print(mBufferET);

 

 

public static String addBlank(String str, int length)

    {

        if (str == null)

        {

            str="";

        }

        int strLen = str.getBytes().length;

        //System.out.println(strLen);

        int lengthPerChar = strLen/str.length();

        //System.out.println(lengthPerChar);

       

        if (strLen == length)

        {

            return str;

        }

        else if (strLen < length)

        {

            int temp = length - strLen;

            String tem = "";

            for (int i = 0; i < temp; i++)

            {

                for (int j = 0; j < lengthPerChar; j++)

                {

                   tem = tem + " ";

                }

            }

            return str + tem;

        }

        else

        {

            return str;

        }

    }

   

    public static String addBlankNum(String str, int length)

    {

        if (str == null)

        {

            str="";

        }

        int strLen = str.getBytes().length;

        //System.out.println(strLen);

        int lengthPerChar = strLen/str.length();

        //System.out.println(lengthPerChar);

       

        if (strLen == length)

        {

            return str;

        }

        else if (strLen < length)

        {

            int temp = length - strLen;

            String tem = "";

            //if(str.contains("."))   tem = tem + " ";

            for (int i = 0; i < temp; i++)

            {

                for (int j = 0; j < lengthPerChar; j++)

                {

                   tem = tem + "  ";

                }

            }

            return str + tem;

        }

        else

        {

            return str;

        }

 }

 

汉字效果较好,数字效果仍待改进。

你可能感兴趣的:(java)