简体   繁体   中英

java string format, replace “”

I want to ask what the "%" + something + "" does in java? And can't we just use "=" instead of replacing " " with "=" ?

bar = String.format("%" + percentage +"s", " ").replace(" ", "=")

Yes. It is possible to write directly like this.

bar = String.format("%" + percentage +"s", "=");

That depends a bit on what percentage is; if it is (as I assume) an int, your code just prints "=" to the screen "percentage" times

int percentage = 20;
System.out.println(String.format("%" + percentage +"s", " ").replace(" ", "="));
//prints ====================

If that is the intention, you can't just leave the replace part out - or more specifically: it won't give you the same result:

System.out.println(String.format("%" + percentage +"s", "="));
//prints                    =

Explanation:

The format("%" + percentage +"s", ...) brings the second parameter to the length you have given (in this case percentage). If the length is shorter than the second parameter, it will add spaces on the left until the desired length is reached.

The first version uses that as a "trick" and replaces the spaces generated afterwards with a "=".

The second version just says: take this "=" and add spaces on the left until it has reached the desired length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM