我嘗試搜索類似的執行緒,但找不到太多。
我正在嘗試縮短以下陳述句,使其少于 120 個字符(當前為 145 個):
return (String.format("I am driving a %s and I love it. It has a top speed of %d miles per hour and it is worth %d", carMake, topSpeed, value));
謝謝!
uj5u.com熱心網友回復:
您可以在某些行中破壞字串文字:
return String.format(
"I am driving a %s and I love it. "
"It has a top speed of %d miles per hour and "
"it is worth %d",
carMake, topSpeed, value);
可以根據需要更改格式,但請注意每行末尾的空白區域(但最后一行)。
字串文字的連接是由編譯器完成的,因此以這種方式拆分字串文字時不會造成性能損失。
uj5u.com熱心網友回復:
將字串存盤在變數中
String strToFormat = "I am driving a %s and I love it. It has a top speed of %d miles per hour and it is worth %d";
return String.format(strToFormat, carMake, topSpeed, value);
uj5u.com熱心網友回復:
如果你想要多行輸出,你也可以這樣做。它成為 Java 15 中的官方構造。
String carMake = "Ferrari";
int topSpeed = 100;
int value = 250000;
String s =
"""
I am driving a %s and I love it.
It has a top speed of %d miles per hour and
it is worth $%,d.
""".formatted(carMake, topSpeed, value);
System.out.println(s);
印刷
I am driving a Ferrari and I love it.
It has a top speed of 100 miles per hour and
it is worth $250,000.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429459.html
上一篇:列印流字串的一部分?
