Say I have the string 123456789. I know that I want to replace indexes 3-5 of the string. (4, 5, and 6). Keep in mind that the replacement probably isn’t 3 characters, I might want to end up with 123foobar789.
What’s the best way to do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Firstly, you cannot do it1, since a
Stringis immutable in java.However, you can create a new String object with the desired value, using the
String#substring()method (for example):If you do want to achieve it efficiently, you could avoid creating some intermediate strings used by the concatinating and
substring()method.However, if it is not done in a very tight loop – you should probably ignore it, and stick with the first and more readable solution.
(1) not easily anyway, it can be done with reflection – but it should be avoided.