Create a string with n characters

前端 未结 27 1167
猫巷女王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: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);
    

提交回复
热议问题