Vincent Zhou
Vincent Zhou

Reputation: 141

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(" ", "=")

Upvotes: 0

Views: 969

Answers (2)

JensS
JensS

Reputation: 1151

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.

Upvotes: 0

Procrastinator
Procrastinator

Reputation: 2674

Yes. It is possible to write directly like this.

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

Upvotes: 1

Related Questions