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
DDDOriginal
2024-12-20 13:58:10971browse

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';

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

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

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!

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