どうも、ちょげ(@chogetarou)です。
文字列(string)の空白を全て削除する方法を紹介します。
方法

文字列(string)の空白を全て削除するには、replaceAll()を使います。
まず、文字列からreplaceAll()を呼び出します。
そして、replaceAll()の第1引数に「”\\s+“」、第2引数に空文字を指定します。
//text=対象の文字列
String result = text.replaceAll("\\s+", "");
上記のreplaceAll()は、呼び出した文字列の半角の空白を削除した文字列を生成します。
もし、全角と半角の両方の空白を削除したい場合は、replaceAll()の第1引数に半角と全角の両方にマッチするパターンを指定します。
//[]内に半角と全角の空白を1文字ずつ入力
String result = text.replaceAll("[ ]", "");
使用例
使用例1
public class Main {
public static void main(String[] args) throws Exception {
String text = " He ll o ,W or l d";
String result = text.replaceAll("\\s+", "");
System.out.println(result);
}
}
出力:
Hello,World
使用例2
public class Main {
public static void main(String[] args) throws Exception {
String text = " He l lo ,W or ld "; //全角の空白あり
//全角と半角の両方を削除
String result = text.replaceAll("[ ]", "");
System.out.println(result);
}
}
出力:
Hello,World





コメント