Create a string with n characters

前端 未结 27 950
猫巷女王i
猫巷女王i 2020-11-28 22:12

Is there a way in java to create a string with a specified number of a specified character? In my case, I would need to create a string with 10 spaces. My current code is:

相关标签:
27条回答
  • 2020-11-28 22:56

    This worked out for me without using any external libraries in Java 8

    String sampleText = "test"
    int n = 3;
    String output = String.join("", Collections.nCopies(n, sampleText));
    System.out.println(output);
    

    And the output is

    testtesttest
    
    0 讨论(0)
  • 2020-11-28 22:57

    For good performance, combine answers from aznilamir and from FrustratedWithFormsDesigner

    private static final String BLANKS = "                       ";
    private static String getBlankLine( int length )
    {
        if( length <= BLANKS.length() )
        {
            return BLANKS.substring( 0, length );
        }
        else
        {
            char[] array = new char[ length ];
            Arrays.fill( array, ' ' );
            return new String( array );
        }
    }
    

    Adjust size of BLANKS depending on your requirements. My specific BLANKS string is about 200 characters length.

    0 讨论(0)
  • 2020-11-28 22:57

    A simple method like below can also be used

    public static String padString(String str, int leng,char chr) {
            for (int i = str.length(); i <= leng; i++)
                str += chr;
            return str;
        }
    
    0 讨论(0)
  • 2020-11-28 22:58

    I highly suggest not to write the loop by hand. You will do that over and over again during the course of your programming career. People reading your code - that includes you - always have to invest time, even if it are just some seconds, to digest the meaning of the loop.

    Instead reuse one of the available libraries providing code that does just that like StringUtils.repeatfrom Apache Commons Lang:

    StringUtils.repeat(' ', length);
    

    That way you also do not have to bother about performance, thus all the gory details of StringBuilder, Compiler optimisations etc. are hidden. If the function would turn out as slow it would be a bug of the library.

    With Java 11 it becomes even easier:

    " ".repeat(length);
    
    0 讨论(0)
  • 2020-11-28 23:00

    Since Java 11 you can simply use String.repeat(count) to solve your problem.

    Returns a string whose value is the concatenation of this string repeated count times.

    If this string is empty or count is zero then the empty string is returned.

    So instead of a loop your code would just look like this:

    " ".repeat(length);
    
    0 讨论(0)
  • 2020-11-28 23:00

    How about this?

    char[] bytes = new char[length];
    Arrays.fill(bytes, ' ');
    String str = new String(bytes);
    
    0 讨论(0)
提交回复
热议问题