どうも、ちょげ(@chogetarou)です。
文字列(string)を空白ごとに分割した配列に変換する方法を紹介します。
方法

文字列(string)を空白ごとに分割するには、split()を使います。
まず、文字列からsplit()を呼び出します。
そして、split()の引数に「”\s+”」を指定します。
String[] result = text.split("\s+");
上記のsplit()は、呼び出した文字列を空白ごとに分割した配列を戻り値として返します。
もし、半角と全角の空白で分割する場合は、split()の引数に「"[\s ]+"
」(sの後に全角の空白)を指定します。
//半角と全角の空白で分割する
String[] result = text.split("[\s ]+");
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = "Taro Jiro Saburo Siro";
String[] result = text.split("[\s ]+");
for (String c : result) {
System.out.println(c);
}
}
}
出力:
Taro
Jiro
Saburo
Siro
コメント