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

文字列(string)の空白を全て削除するには、replaceAll()を使います。
まず、文字列からreplaceAll()を呼び出します。
そして、replaceAll()の第1引数に「"\\s+"
」、第2引数に空文字を指定します。
String result = text.replaceAll("\\s+", "");
上記のsubstring()は、呼び出した文字列の空白を全て削除した文字列を返します。
もし、全角の空白を含めて削除したい場合は、replaceAll()の第1引数に「"[\\s+ ]"
」(\\s+の後に全角の空白)を指定します。
//「\\s+」の後に全角の空白を入力
String result = text.replaceAll("[\\s+ ]", "");
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = " He l lo ,W orld ";
text = text.replaceAll("[\\s+ ]", "");
System.out.println(text);
}
}
コメント