[英]Replace spaces with '-' with string.format?
我正在打印事物列表,並用空格格式化了文本。 但是我只希望所有的破折號而不是空格。...我無法弄清楚或找到一種方法來做到這一點,同時保持文本的格式正確。
這是我的格式代碼:
System.out.println(String.format("Word:%11s-----------Hash Value:%5s ",arrayString[i],arrayNums[i]));
這是示例輸出:
Word: DO-----------Hash Value: 2
Word: END-----------Hash Value: 3
Word: ELSE-----------Hash Value: 4
Word: CASE-----------Hash Value: 5
Word: DOWNTO-----------Hash Value: 6
Word: GOTO-----------Hash Value: 7
Word: TO-----------Hash Value: 8
Word: OTHERWISE-----------Hash Value: 9
Word: TYPE-----------Hash Value: 10
Word: WHILE-----------Hash Value: 11
Word: CONST-----------Hash Value: 12
所需的輸出:
Word:---------DO-----------Hash Value:----2
這將起作用。
String stringToPrint = String.format("Word:%11s-----------Hash Value:%5s ",arrayString[i],arrayNums[i]);
stringToPrint = stringToPrint.replace(' ', '-');
System.out.println(stringToPrint);
你可以做
System.out.println(String.format("Word:%11s-----------Hash Value:%5s ".replace(" ", "ƒ"),
arrayString[i], arrayNums[i]).replace(" ", "-").replace("ƒ", " "));
像這樣嗎
public class Dash
{
public static void main (String[] args)
{
String dashes = "-------------";
String[] verbs =
{ "DO", "END", "ELSE", "CASE", "DOWNTO", "GOTO", "TO", "OTHERWISE", "TYPE",
"WHILE", "CONST" };
for (String verb : verbs)
System.out.printf ("%s%s%s%n", dashes.substring (verb.length ()), verb, dashes);
}
}
這使
-----------DO-------------
----------END-------------
---------ELSE-------------
---------CASE-------------
-------DOWNTO-------------
---------GOTO-------------
-----------TO-------------
----OTHERWISE-------------
---------TYPE-------------
--------WHILE-------------
--------CONST-------------
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.