Formatting my string

I need to write currency values, for example, $ 35.40 (thirty-five dollars and forty cents) and after that I want to write a few "****"

so at the end it will be: thirty five dollars and forty cents********* at the maximum value of 100 characters

I asked a question about something very likely, but I could not understand the main team.

String format = String.format("%%-%ds", 100);
String valorPorExtenso = String.format(format, new Extenso(tituloTO.getValor()).toString());

What do I need to change in format to put ***at the end of my sentence? Now it puts spaces.

+3
source share
5 answers

This formatting will give you 100 characters including a string

String.format("%-100s", "thirty five dollars and forty cents.").replaceAll("  ", "**");

UPDATE:

String.format("%-100s", "thirty five dollars and forty cents.").replaceAll("  ", "**").replace("* ", "**");
+1
source

I would do:

String line = "thirty five dollars and forty cents";
StringBuilder lineBuffer = new StringBuilder(line);
for(int i=0; i < 100 - line.length(); i++){
    lineBuffer.append("*");
}
line = lineBuffer.toString();
+2
source

commons-lang http://commons.apache.org/lang/api-release/index.html

, 100 .

http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html#rightPad%28java.lang.String,%20int,%20java.lang.String%29

- 100 '*'.

:

StringBuilder sb= new StringBuilder(new Extenso(tituloTO.getValor()).toString());
sb.append(STARS_STR);
String val= sb.substring(0, 100);

, .

+2

You cannot use String.format (), however, there are utils to do this in apache StringUtils. Or just write a little method that adds * for the specified length.

0
source

Source: https://habr.com/ru/post/1784059/


All Articles