我会解释一下自己,我想将一个replaceLast添加到String类中,这可能吗?目前我使用的是自制的方法,即:
public static String replaceLast(String string, String toReplace, String replacement) {
int pos = string.lastIndexOf(toReplace);
if (pos > -1) {
return string.substring(0, pos) + replacement + string.substring(pos + toReplace.length(), string.length());
} else {
return string;
}
}
有什么办法可以使用这种方法,例如:
String str = "Hello World";
str.replaceLast("l", "");
//being the first String the one to be replaced and the second one the replacement
就像使用一样:
String str = "Hello World";
str.replaceFirst("o", "e");
最佳答案
不,你不能。 String 类是最终类,因此您不能对其进行子类化。 Java 也无法将行为附加到现有类。 Kotlin有这个功能,但它实际上是用静态方法实现的。
关于java - 我可以向 String 类添加新方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58635611/