Java は複数行の文字列をサポートしていますか? 質問する

Java は複数行の文字列をサポートしていますか? 質問する

Perl 出身の私には、ソース コード内に複数行の文字列を作成する「ヒアドキュメント」という手段が欠けていることは確かです。

$string = <<"EOF"  # create a three-line string
text
text
text
EOF

Java では、複数行の文字列を最初から連結するため、各行に面倒な引用符とプラス記号を付ける必要があります。

もっと良い代替案は何でしょうか? プロパティ ファイルで文字列を定義しますか?

編集: 2 つの回答では、StringBuilder.append() がプラス表記よりも好ましいとされています。なぜそう思うのか、詳しく説明していただけますか? 私にとっては、まったく好ましいようには思えません。複数行の文字列は第一級言語構成要素ではないという事実を回避する方法を探しています。つまり、第一級言語構成要素 (プラスによる文字列連結) をメソッド呼び出しに置き換えることは絶対に望んでいません。

編集: 質問をさらに明確にすると、パフォーマンスについてはまったく心配していません。保守性と設計の問題について心配しています。

ベストアンサー1


: この回答は Java 14 以前に適用されます。

テキストブロック(複数行リテラル)はJava 15で導入されました。この答え詳細については。


複数行のリテラルを実行したいようですが、Java には存在しません。

最善の代替案は、単に連結された文字列です+。他のいくつかのオプション (StringBuilder、String.format、String.join) は、文字列の配列から開始する場合にのみ適しています。

このことを考慮:

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";

StringBuilder

String s = new StringBuilder()
           .append("It was the best of times, it was the worst of times,\n")
           .append("it was the age of wisdom, it was the age of foolishness,\n")
           .append("it was the epoch of belief, it was the epoch of incredulity,\n")
           .append("it was the season of Light, it was the season of Darkness,\n")
           .append("it was the spring of hope, it was the winter of despair,\n")
           .append("we had everything before us, we had nothing before us")
           .toString();

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,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

Java8と比較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,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

特定のシステムで改行が必要な場合は、 を使用するSystem.lineSeparator()か、%nで を使用する必要がありますString.format

もう 1 つのオプションは、リソースをテキスト ファイルに入れて、そのファイルの内容を読み取ることです。これは、クラス ファイルが不必要に肥大化することを避けるために、非常に大きな文字列の場合に適しています。

おすすめ記事