Home >Java >javaTutorial >How Can I Modify a Specific Character in a Java String?

How Can I Modify a Specific Character in a Java String?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 18:23:14709browse

How Can I Modify a Specific Character in a Java String?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn