Is there a simple way to add a character or another String n-times to an existing String?
I couldn’t find anything in String
, Stringbuilder
, etc.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
but you should use StringBuilder instead, and save memory
Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).
Something like:
Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.
Its better to use
StringBuilder
instead ofString
because String is an immutable class and it cannot be modified once created: in String each concatenation results in creating a new instance of the String class with the modified string.How I did it:
Now add it to your
StringBuilder
or
String
Apache
commons-lang3
hasStringUtils.repeat(String, int)
, with this one you can do (for simplicity, not withStringBuilder
):Since it is open source, you can read how it is written. There is a minor optimalization for small n-s if I remember correctly, but most of the time it uses
StringBuilder
.