How to replace a character in a Java string?

In Java, the replace method of the String class can be used to replace a character in a string. The replace method takes two parameters: the first parameter is the character to be replaced, and the second parameter is the character to replace it with. Here is an example code:

String str = "Hello World";
String newStr = str.replace('o', 'a');
System.out.println(newStr); // 输出: Hella Warld

In the example above, we replaced the character ‘o’ with the character ‘a’ in the string and obtained the new string, newStr, by calling the replace method.

bannerAds