To change a specific character of a string in Java, you can use the charAt
method of the String
class to get the character at a specific index, and then use the substring
method to create a new string with the modified character.
Here's an example of how you might do this:
String str = "Hello, World!"; char ch = 'a'; // The new character int index = 1; // The index of the character to be replaced String newStr = str.substring(0, index) + ch + str.substring(index + 1); System.out.println(newStr); // Output: Hallo, World!Source:ttual.wwwuri.com
In this example, the substring
method is used to create a new string by concatenating three substrings: the substring before the character to be replaced, the new character, and the substring after the character to be replaced.