對於熟悉 Perl 的人來說,「here-document」是一個在其中創建多行字串的有用工具。原始碼.然而,在 Java 中,在每行上使用引號和加號手動連接字串可能會非常乏味且麻煩。
雖然 Java 中沒有與「here-document」語法直接等效的語法,但有幾種替代方法考慮有效地建立多行字串。
1.使用加號運算子 ( ) 連接字串
最簡單的方法是使用加號運算子 ( ) 手動連接字串。這涉及使用字串文字 ""n"" 根據需要明確添加換行符:
String s = "It was the best of times, it was the worst of times\n" + "it was the age of wisdom, it was the age of foolishness\n" + "it was the epoch of belief, it was the epoch of incredulity\n" + "it was the season of Light, it was the season of Darkness\n" + "it was the spring of hope, it was the winter of despair\n" + "we had everything before us, we had nothing before us";
2。 StringBuilder.append()
StringBuilder 類別提供了一個名為append() 的方法,可用來將字串或其他資料附加到字串產生器。雖然此技術看起來不如使用加號運算子簡潔,但它提供了某些優點,例如增強的效能和執行緒安全性。
StringBuilder sb = new StringBuilder(); sb.append("It was the best of times, it was the worst of times"); sb.append("it was the age of wisdom, it was the age of foolishness"); // ... String s = sb.toString();
3. String.join()
在Java 8 中引入,String.join() 允許使用指定的分隔符號將多個字串組合成單一字串。要建立多行字串,可以設定分隔符號來表示所需的換行符:
String s = String.join("\n" , "It was the best of times, it was the worst of times" , "it was the age of wisdom, it was the age of foolishness" // ... );
4。 String.format()
String.format() 是一個基於模式格式化字串的強大工具。它也可用於透過將換行符合並到格式模式中來建立多行字串:
String s = String.format("%s\n%s\n%s\n%s\n%s\n%s" , "It was the best of times, it was the worst of times" , "it was the age of wisdom, it was the age of foolishness" // ... );
5。儲存在文字檔案中
對於特別大的字串,將內容儲存在單獨的文字檔案中,然後將檔案的內容讀入字串中可能會很有幫助。這種方法可以幫助避免帶有大字串文字的類別文件膨脹。
以上是如何在Java中高效創建多行字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!