[Java]文字列(string)の末尾の文字を置換するには?

どうも、ちょげ(@chogetarou)です。

文字列(string)の末尾の文字を置換する方法を紹介します。

スポンサーリンク

方法

文字列(string)の最後の文字を置換する方法は、2つあります。

replaceFirst()

ひとつは、replaceFirst()を使う方法です。

まず、文字列からreplaceFirst()を呼び出します。

そして、replaceFirst()の第1引数に「”.$”」、第2引数に置換後の文字を指定します。

//text=対象の文字列、replace=置換後の文字列
String result = text.replaceFirst(".$", replace);

上記のreplaceFirst()は、呼び出した文字列の末尾の文字を置換した文字列を生成します。

使用例

public class Main {

    public static void main(String[] args) throws Exception {
        String text = "Hello,World";
        
        String result = text.replaceFirst(".$", "*");
        
        System.out.println(result);
    }
}
出力:
Hello,Worl*

replaceAll()

もうひとつは、replaceAll()を使う方法です。

まず、文字列からreplaceAll()を呼び出します。

そして、replaceAll()の第1引数に「”.$”」、第2引数に置換後の文字を指定します。

//text=対象の文字列、replace=置換後の文字列
String result = text.replaceAll(".$", replace);

上記のreplaceAll()は、呼び出した文字列の末尾の文字を置換した文字列を生成します。

使用例

public class Main {

    public static void main(String[] args) throws Exception {
        String text = "Hello,World";
        
        String result = text.replaceAll(".$", "*");
        
        System.out.println(result);
    }
}
出力:
Hello,Worl*

まとめ

文字列(string)の最後の文字を置換する方法は、次の2つです。

  • replaceFirst()を使う方法
    String result = text.replaceFirst(".$", replace);
  • replaceAll()を使う方法
    String result = text.replaceAll(".$", replace);

コメント

タイトルとURLをコピーしました