Replacing Characters in Strings
Question: How can I change a single character in a Java string at a specific index?
Example:
String myName = "domanokz"; myName.charAt(4) = 'x'; // Throws an error
Answer: Strings in Java are immutable, meaning once created, they cannot be modified. To change a character, you'll need to create a new string containing the desired change.
One solution is to use the substring method to extract the desired portion of the old string and concatenate it with the new character:
String newName = myName.substring(0, 4) + 'x' + myName.substring(5);
Another approach is to use a StringBuilder, which provides mutable string operations:
StringBuilder myName = new StringBuilder("domanokz"); myName.setCharAt(4, 'x'); System.out.println(myName); // Prints "domanoxz"
The above is the detailed content of How Can I Modify a Specific Character in a Java String?. For more information, please follow other related articles on the PHP Chinese website!