2

From the post String Builder Replace() is faster then string replace() in .NET language

I want to know if same answer is valid for java as well or not.

I checked and found

StringBuilder builder = ...;
builder = new StringBuilder(builder.toString().replace("from", "to"));

is inefficient as StringBuilder.toString() is an expensive operation.

Why JAVA does not have replace method in string builder class ?

Community
  • 1
  • 1
T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • 2
    https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#replace(int,%20int,%20java.lang.String) – jsheeran May 30 '17 at 10:13
  • 1
    There is a `replace(int, int, String)` method and also an `indexOf(String, int)` method. I guess you can use these to write your own `replace(String, String)` method. – Sweeper May 30 '17 at 10:14
  • Docs does not mentioned this thing that is why i came here ! – T-Bag May 30 '17 at 10:14
  • +jsheeran It's not what OP is trying to achieve. – Nyamiou The Galeanthrope May 30 '17 at 10:16
  • Who knows? Why doesn't C# have something that Java has? Like...applets! – Kayaman May 30 '17 at 10:36
  • 1
    @Kayaman-- Don't compare apple and oranges I am talking about similar functionality here that both language's posses. – T-Bag May 30 '17 at 10:37
  • Well, because they're not the same language. I was being facetious about applets, but while Java and C# resemble each other, they're not the same language and therefore there are even significant differences in how some things are handled. I don't think either of the language's philosophy is to have all the functionality of the other one. Also, it's not JAVA, it's Java. – Kayaman May 30 '17 at 10:43

1 Answers1

3

From the documentation :

StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations

for that the StringBuilder::replace is like :

public StringBuilder replace(int start, int end, String str)

Instead of String::replace, because it is treated like an array and not a String

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140