LoginSignup
1
1

More than 3 years have passed since last update.

文字列の分割(Java)

Posted at

はじめに

文字の分割のいろいろなパターンをまとめてみた。

区切り文字1つ、第2引数なしのパターン

public class Sample {
    public static void main(String[] args) {
        String str = "1,2,3,4";
        String[] strs = str.split(",");
        for (String num : strs) {
            System.out.println(num);
        }
        System.out.println("配列の数:"+strs.length);
    }
}
実行結果.
1
2
3
4
配列の数:4

区切り文字1つ、第2引数ありのパターン(第2引数が0より大きいとき)

public class Sample {
    public static void main(String[] args) {
        String str = "1,2,3,4";
        String[] strs = str.split(",",3);
        for (String num : strs) {
            System.out.println(num);
        }
        System.out.println("配列の数:"+strs.length);
    }
}
実行結果.
1
2
3,4
配列の数:3

第2引数は要素数を指定する。
今回の場合は3を指定したため、要素数が3つになる。

区切り文字1つ、第2引数ありのパターン(第2引数が負の値のとき)

public class Sample {
    public static void main(String[] args) {
        String str = "1,2,3,4,";
        String[] strs = str.split(",",-1);
        for (String num : strs) {
            System.out.println(num);
        }
        System.out.println("配列の数:"+strs.length);
    }
}
実行結果.
1
2
3
4

配列の数:5

第2引数が負の値のときは配列の要素数は制限されず、配列の終わりの空の文字列は削除されない。
今回の場合は-1を指定したが負の値のため要素数は制限されていない。また、空の文字列も含んでいる。

区切り文字が複数のとき

public class Sample {
    public static void main(String[] args) {
        String str = "1+2=3";
        String[] strs = str.split("[=+]");
        for (String num : strs) {
            System.out.println(num);
        }
        System.out.println("配列の数:"+strs.length);
    }
}
実行結果.
1
2
3
配列の数:3

区切り文字を複数指定する場合は[]内に区切る文字を入れる。

区切り文字を含めて区切るとき

public class Sample {
    public static void main(String[] args) {
        String str = "1,2,3";
        String[] strs = str.split("(?<=,)");
        for (String num : strs) {
            System.out.println(num);
        }
        System.out.println("配列の数:"+strs.length);
    }
}
実行結果.
1,
2,
3
配列の数:3

区切り文字を含める場合は(?<=)を使用する。

複数の区切り文字を含めて区切るとき

public class Sample {
    public static void main(String[] args) {
        String str = "1,2a3";
        String[] strs = str.split("(?<=[,a])");
        for (String num : strs) {
            System.out.println(num);
        }
        System.out.println("配列の数:"+strs.length);
    }
}
実行結果.
1,
2a
3
配列の数:3

複数の区切り文字を含める場合は(?<=[])の[]内に区切る文字を入れる。

1
1
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
1
1