Andrew Powell
Andrew Powell

Reputation: 21

Can I add a char to a variable specified position within a string?

OK, this is the line I am working on:

newstring.charAt(w) += p;

trying to add a character/char (p) to the string 'newstring' at a particular position within the string which is defined by int 'w'. Is this possible?

Upvotes: 2

Views: 245

Answers (2)

biziclop
biziclop

Reputation: 49744

Strings are immutable in Java, so the answer is no. But there are many ways around it. The easiest is to create a StringBuilder and use the setCharAt() method. Or insert() if you want to insert a new character at a given position.

If you make multiple modifications to your string, you can (and indeed should) reuse your StringBuilder.

Upvotes: 4

Rohit Jain
Rohit Jain

Reputation: 213261

Well, you can't modify your string, because Strings are immutable in Java. If you try to change the string, you will get a new string object as a result.

Now, you can use String#substring method for that, using which you can get new string which is generated by some concatenation of substring of original string.: -

str = str.substring(0, w) + "p" + str.substring(w);

But, of course, using StringBuilder as specified in @biziclop's answer is the best approach you can follow.

Upvotes: 2

Related Questions