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
Release: 2024-12-21 18:23:14
Original
632 people have browsed it

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
Copy after login

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);
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template