我打印出一系列内容,然后用空格格式化文本。但是我只想要所有破折号而不是空格....我无法弄清楚或找到一种方法来做到这一点,同时保持文本格式正确。
这是我的格式代码:
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
答案 0 :(得分:1)
这样可行。
String stringToPrint = String.format("Word:%11s-----------Hash Value:%5s ",arrayString[i],arrayNums[i]);
stringToPrint = stringToPrint.replace(' ', '-');
System.out.println(stringToPrint);
答案 1 :(得分:0)
你可以做到
System.out.println(String.format("Word:%11s-----------Hash Value:%5s ".replace(" ", "ƒ"),
arrayString[i], arrayNums[i]).replace(" ", "-").replace("ƒ", " "));
答案 2 :(得分:0)
这样的东西?
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-------------