2

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

@JigarJoshi.. No, the first substring returns string till index w - 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.