[英]Java carriage return \r doesn't seem to work correctly
這是我的 java 代碼:
// file name is Strings.java
public class Main {
public static void main(String[] args){
String txt = "Hello\rWorld!";
System.out.println(txt);
String txt2 = "Trying\rthis";
System.out.println(txt2);
}
}
我試圖從我的終端執行它,看到了這個:
$ java Strings.java
World!
thisng
我也嘗試從VS Code
執行此操作,結果相同。 有誰知道這里發生了什么?
謝謝!
———
編輯:
我試圖執行類似於 (this)[https://www.w3schools.com/java/tryjava.asp?filename=demo_strings_r] 的東西。 我知道我根本不必使用 \r; 我只是想知道為什么輸出是這樣的。
這取決於操作系統:Linux ( \n
)、Mac ( \r
)、Windows ( \r\n
)。 都有不同new line
。 請參閱Java 中的向字符串添加換行符。
要獲得實際組合,請使用:
System.lineSeparator()
根據你的例子:
System.out.println("Hello" + System.lineSeparator() + "World!");
System.out.println("Trying" + System.lineSeparator() + "this");
Output:
$ java Strings.java
Hello
World!
Trying
World!
this
這有點難看,但是一個通用的解決方案。
PS作為替代方案,您可以使用System.out.format()
代替:
System.out.format("Hello%nWorld!%n");
System.out.format("Trying%nthis%n");
PPS我認為一般來說最好建立一個行列表並使用System.out.println()
:
Arrays.asList("Hello", "World!").forEach(System.out::println);
Arrays.asList("Trying", "this!").forEach(System.out::println);
您還可以使用帶有%n
的format
,它被平台行分隔符替換,因此可以使用:
System.out.format("Hello%nWorld!%n");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.