0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javaで改行コード、特殊文字のエスケープをせずに文字列を扱う方法について

Last updated at Posted at 2024-08-01

文字列の扱いについて

Java15からテキストブロック(TextBlocks)が追加になりました。
今まで文字列の扱いについては、改行が必要な場合は改行コードを含める必要があり、特殊文字はエスケープする等の制御が必要でしたが、テキストブロックを利用することで文字列のそのまま表現できるため読み易さが格段に上がります。

正規表現を取り扱う場合は読み易くなったと感じます。
ということで、今回はテキストブロックについて紹介したいと思います。

テキストブロックについて

テキストブロックはJavaの文字列表現の代替形式となります。従来の2重引用符が使用できる場所であればどこでも使用できます。
テキストブロックの使用例について紹介します。

  • テキストブロックの構文
    public static void main(String[] args) {

        // 従来の文字列
        String dqName = "Pat Q. Smith";
        // テキストブロック
        String tbName = """
                Pat Q. Smith""";

        System.out.println(dqName.equals(tbName));
        System.out.println(dqName == tbName);
    }
  • Stringとテキストブロックを結合する場合
    public static void main(String[] args) {

        // 結合
        String str = "The old";
        String tb = """
                the new""";
        System.out.println(str + " and " + tb + ".");
    }
  • テキストブロック内で改行をする場合
    public static void main(String[] args) {

        System.out.println("""
                This is the first line
                This is the second line
                This is the third line""");
    }
  • substringを使用する
    public static void main(String[] args) {

        System.out.println("""
                        John Q. Smith""".substring(8).equals("Smith"));
    }
  • formatted(string.format)を使用する
    public static void main(String[] args) {

        String output = """
                        Name: %s
                        Phone: %s
                        Address: %s
                        Salary: $%.2f""".formatted("John Doe", "555-1234", "123 Main St",
                        50000.00);
        System.out.println(output);
    }

まとめ

Java15から導入されたテキストブロックについて紹介しました。
改行文字を扱う場合にはとても有用な機能となりますので、機会があれば利用してきましょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?