どうも、ちょげ(@chogetarou)です。
文字列(string)の末尾からN文字を置換する方法を紹介します。
方法

文字列(string)の後ろからN文字を置換する方法は、2つあります。
replaceFirst()
ひとつは、replaceFirst()を使う方法です。
まず、文字列からreplaceFirst()を呼び出します。
そして、replaceFirst()の第1引数に「”.{n}$”」(n=置換する文字数)、第2引数に置換後の文字を指定します。
//text=対象の文字列, n=置換する文字数, replace=置換後の文字列
String result = text.replaceFirst(".{n}$", replace);
上記のreplaceFirst()は、呼び出した文字列の後ろからN文字を置換した文字列を生成します。
使用例
public class Main {
public static void main(String[] args) throws Exception {
String text = "Hello,World";
String result = text.replaceFirst(".{5}$", "*****");
System.out.println(result);
}
}
出力:
Hello,*****
substring()
もうひとつは、substring()を使う方法です。
まず、「+」の左辺で文字列からsubstring()を呼び出します。
substring()の第1引数に「0」、第2引数に文字列の文字数を置換する文字数で引いた値を指定します。
そして、「+」の右辺に置換後の文字列を指定します。
//str=対象の文字列, n=置換する文字数, replace=置換後の文字列
String result = str.substring(0, str.length() - n) + replace;
上記の「+」は、呼び出した文字列の後ろからN文字を右辺の文字列に置換した文字列を生成します。
使用例
public class Main {
public static String replaceLastN(String str, int n, String replace) {
return str.substring(0, str.length() - n) + replace;
}
public static void main(String[] args) throws Exception {
String text = "Hello,World";
int n = 5; //置換する文字数
String result = replaceLastN(text, n, "*****");
System.out.println(result);
}
}
出力:
Hello,*****
まとめ
文字列(string)の後ろからN文字を置換する方法は、次の2つです。
- replaceFirst()を使う方法
String result = text.replaceFirst(".{n}$", replace);
- substring()を使う方法
String result = str.substring(0, str.length() - n) + replace;
コメント