2
2

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 3 years have passed since last update.

【Java】文字列を分割する方法

Posted at

プログラミング勉強日記

2020年12月8日
3日連続JavaのString型の扱いになるが、今日は文字列を分解するsplitメソッドの使い方をまとめる。

splitメソッドとは

 文字列を分割して、分割した文字列を配列として格納するメソッド。区切りたい文字には正規表現を設定することができ、分割回数の数値によって空白文字の消去にも使うことができる。String型の配列として返す。(正規表現についてはこちらの記事で詳しく扱っている。)
 csvファイルといったカンマ区切りの文字列のファイルを操作するときによく使われる。

splitメソッドの書き方
文字列.split(区切りたい文字列, 分割回数);
サンプルコード
public class Main {
  public static void main(String[] args) {
    String str = "white,green,blue,red";
    String[] colors = str.split(",");
    for (int i = 0; i < colors.length; i++) {
      System.out.println(colors[i]);
    }
  }
}
実行結果
white
green
blue
red

文字列の数を指定する場合

 splitメソッドの第2引数に1以上の整数を設定することで、文字列の分割回数を制御することができる。

サンプルコード
public class Main {
  public static void main(String[] args) {
    String str = "white,green,blue,red,,";
    String[] colors = str.split(",", 3);
    for (int i = 0; i < colors.length; i++) {
      System.out.println(colors[i]);
    }
  }
}
実行結果
white
green
blue,red

末尾の空白文字の要素を削除する場合

 第2引数が0もしくは何も設定しない場合は、末尾の空白文字を削除することができる。削除したくないときは-1といったマイナスの値を設定する。

サンプルコード
public class Main {
  public static void main(String[] args) {
    String str = "white,green,blue,red,,";
    String[] colors = str.split(",", 0);
 
    System.out.println("第二引数が0の場合");
    for (int i = 0; i < colors.length; i++) {
      System.out.println(i + ":" + colors[i]);
    }

    colors = str.split(",", -1);
    System.out.println("第二引数が-1の場合");
    for (int i = 0; i < colors.length; i++) {
      System.out.println(i + ":" + colors[i]);
    }
  } 
}
実行結果
第二引数が0の場合
0:white
1:green
2:blue
3:red

第二引数が-1の場合
0:white
1:green
2:blue
3:red
4:
5:

間にある空白文字を削除する場合

 間の空白文字を削除するときには正規表現を使う。

サンプルコード
public class Main {
  public static void main(String[] args) {
    String str = "white  ,green  ,blue,red";
    String[] colors = str.split("[\\s]*,[\\s]*");
    
    for (int i = 0; i < colors.length; i++) {
      System.out.println(colors[i]);
    }
  }
}
実行結果
white
green
blue
red

参考文献

2分で理解!Javaの文字列を分割するsplitメソッド【Stringクラス】
Javaのsplitの使い方を現役エンジニアが解説【初心者向け】

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?