I want to replace characters in a specific index of a string.

Asked 2 years ago, Updated 2 years ago, 135 views

To replace characters in a specific index in a string

String myName = "domanokz";
myName.charAt(4) = 'x';

I tried this way, but an error occurred. Is there another method?

string java replace indexing character

2022-09-22 22:17

1 Answers

In Java, the string is immutable and cannot be replaced. so To solve the problem, you can create a new string with a specific index changed and substitute it.

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Like this. If you don't like it, use StringBuilder

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

You can do it like this.


2022-09-22 22:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.