Home > Java > javaTutorial > How Can I Replace a Character at a Specific Index in a Java String?

How Can I Replace a Character at a Specific Index in a Java String?

DDD
Release: 2024-12-20 13:58:10
Original
1012 people have browsed it

How Can I Replace a Character at a Specific Index in a Java String?

Mutable Strings and Character Replacement at a Specific Index

Strings in Java are immutable, meaning once created, they cannot be modified. Attempting to alter a character at a specific index, as demonstrated in the code below, will result in an error:

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

Replacing Characters in Strings

There are two primary approaches to replace characters in strings:

1. Concatenation

One method is to create a new string by concatenating the desired characters. In this case, the code could be modified as follows:

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

System.out.println(newName); // Output: domanoxi
Copy after login

2. StringBuilder

Another option is to use the StringBuilder class. StringBuilder objects are mutable and provide various methods for manipulating strings. The code could be rewritten using StringBuilder as follows:

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

System.out.println(myName); // Output: domanoxi
Copy after login

The above is the detailed content of How Can I Replace a Character at a Specific Index 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template