12
6

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

はじめに

タイトルのとおり、業務において文字列から特定の文字を消す必要がありました。

その処理をどのように行ったのかを簡単ではありますが記事にしました。

実装例

今回{}で括られている文字列から{}を消したいとします。

この時下記のようにStringクラスのreplaceメソッドを用いれば、{}を消すことができます。

sample.java
public class Main {
    public static void main(String[] args) throws Exception {
        String test = "{test}";

        String result = test.replace("{", "").replace("}", "");

        System.out.println(result); // test が出力される

        System.out.println(result.length()); // 4 が出力される
    }
}

replaceの第一引数に消したい文字を指定し、第二引数に空文字を渡すことで特定の文字の消去を実現しています。

まとめ

文字列から特定の文字を消すにはStringクラスのreplaceメソッドを用い、第一引数に消したい文字列、第二引数に空文字を渡すことで、実現することができます。

よりスマートな方法があれば、ご教示いただけますと幸いです。

この記事が少しでも誰かの役に立てれば幸いです。
最後までお読みいただきありがとうございました。

参考文献

replaceメソッドのJavaDoc

12
6
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
12
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?