如何在Java中直接在控制臺輸出換行符“ ”,而不被解釋為換行?本文提供解決方案,幫助您在Java控制臺程序中,原樣打印包含轉義字符(如換行符)的字符串。
許多程序需要在控制臺中顯示字符串的原始格式,包括其中的轉義字符。 然而,直接打印包含” “的字符串會導致換行。
以下代碼示例演示了問題:
public static void main(String[] args) { String b = String.format("The data download task succeed. %nName:%s ", "1"); System.out.println(b); // 被解釋為換行 String a = "The data download task succeed. " + "Name:1 "; System.out.println(a); // 被解釋為換行 System.out.println(a.equals(b)); //true, 內容相同 }
為了解決這個問題,我們創建了一個輔助函數printWithEscapeSequences:
立即學習“Java免費學習筆記(深入)”;
public static void printWithEscapeSequences(String str) { String replaced = str.replace(" ", "r").replace(" ", "n"); System.out.println(replaced); }
該函數使用replace()方法將字符串中的” “替換為” “,” “替換為” “,從而將換行符轉義為字符串字面量。 改進后的完整代碼如下:
public static void main(String[] args) { String b = String.format("The data download task succeed. %nName:%s ", "1"); printWithEscapeSequences(b); String a = "The data download task succeed. " + "Name:1 "; printWithEscapeSequences(a); System.out.println(a.equals(b)); } public static void printWithEscapeSequences(String str) { String replaced = str.replace(" ", "r").replace(" ", "n"); System.out.println(replaced); }
現在,運行此代碼,您將看到控制臺輸出包含” “和” “的字符串,而不是實際的換行。 這實現了原樣輸出換行符的需求。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END