2

I have a string s composed of two strings s1 and s2, s = s1+s2.

I'd like to be able to modify s1 in another function, and then recompose s with the modified version of s1. I'd like to change s1 so that it takes s2 as a paramater. For example, s1 = "1+" and s2="2", and I'd like s to become "incr(" + s2 + ")".

I could do that by using s1 = "incr(%s2%)" and then s1.replace("%s2%",s2), but what if s1 already contains "%s2%" ? I'd like it to be as generic as possible.

Is there any way to do that ?

Martin Perry
  • 9,232
  • 8
  • 46
  • 114
Car981
  • 261
  • 1
  • 3
  • 11

3 Answers3

4

String is an immutable class, meaning you cannot modify it. All String methods create a new String, instead of modifying the String.

You could however use toCharArray (or StringBuilder for more flexibility), which is mutable.

Jonas Eicher
  • 1,413
  • 12
  • 18
0

If you want editable Strings in Java, use StringBuilder class (http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html). That has multiple methods for mannipulation and replacing substring.

Martin Perry
  • 9,232
  • 8
  • 46
  • 114
0

Use StringBuffer if synchronization is required or else use StringBuilder to reduce the overhead of synchronization. Both are mutable classes. They have many methods to modify the content of String.

MaheshVarma
  • 2,081
  • 7
  • 35
  • 58