0

I'll explain myself, I would want to add a replaceLast into String class, is that possible? At the moment I'm using a self-made method, which is:

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;
            }
        }

Is there any way to be able to use this method like:

String str = "Hello World";
str.replaceLast("l", "");
//being the first String the one to be replaced and the second one the replacement

like it is used:

String str = "Hello World";
str.replaceFirst("o", "e");
ElChusky
  • 39
  • 6
  • 2
    No, you can't modify the `String` class, or any JRE classes, and anyway `String` is immutable so your design is wrong anyway. – user207421 Oct 31 '19 at 01:05
  • You mean `str = str.replaceFirst("o", "e");` – Scary Wombat Oct 31 '19 at 01:07
  • You're right, Scary Wombat. And Mr User207421, what do you mean with "String is immutable so your design is wrong"? My method replaceLast is wrong or the idea of adding the method into the class String? – ElChusky Oct 31 '19 at 01:22
  • Your idea of a method such that calling `str.replaceLast(...)` without storing a result value, as you do in your example, will update anything is wrong. – user207421 Oct 31 '19 at 01:24

1 Answers1

0

No you cannot. String class is final so you cannot sub-class it. Java also cannot attach behavior to an existing class. Kotlin has this feature, but it actually implement it using static method.

Antony Ng
  • 767
  • 8
  • 16