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

【Java】文字列の空白を除去する

Posted at

trim()

文字列の前後の空白を除去したい時は、trimメソッドを使用します。
ただし、文字列途中にある空白は除去の対象外になります。

trim.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

        String str = "   Hello, World   ";
        //文字列前後の空白を除去する
        System.out.println(str.trim());
    }
}
結果
Hello, World

replaceAll()

文字列のすべての空白を除去したい時は、replaceAllメソッドを使用します。

trim.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

        String str = "   Hello, World   ";
        //すべての空白を除去する
        System.out.println(str.replaceAll(" ",""));
    }
}
結果
Hello,World
1
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
1
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?