[英]java string format, replace “”
I want to ask what the "%" + something + ""
does in java? 我想问一下Java中
"%" + something + ""
作用是什么? 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,则您的代码仅在屏幕上“%”次打印“ =”
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). format("%" + percentage +"s", ...)
将第二个参数带到您指定的长度(在本例中为百分比)。 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. 第二个版本只是说:用这个“ =”并在左边添加空格,直到达到所需的长度为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.