Home >Java >javaTutorial >How Can I Replace Characters in a Java String at Specific Indices?
Replacing Characters in a String at Specified Indices
When working with strings in Java, it is often necessary to replace specific characters at designated positions within the string. However, Strings in Java are immutable, meaning that their contents cannot be directly modified.
Incorrect Approach
The code snippet provided:
String myName = "domanokz"; myName.charAt(4) = 'x';
attempts to replace the character at index 4 ('o') with 'x'. However, it will result in an error because Java Strings are immutable.
Solution
To replace a character at a specific index, we can create a new string with the desired changes or use a StringBuilder:
String myName = "domanokz"; String newName = myName.substring(0, 4) + 'x' + myName.substring(5);
This code concatenates the beginning of the string with the replacement character and the end of the string to create a new string with the updated character.
StringBuilder myName = new StringBuilder("domanokz"); myName.setCharAt(4, 'x'); System.out.println(myName);
StringBuilder is a mutable data structure that allows us to modify strings. We first create a StringBuilder object from the original string and then use the setCharAt method to replace the character at the specified index.
The above is the detailed content of How Can I Replace Characters in a Java String at Specific Indices?. For more information, please follow other related articles on the PHP Chinese website!