How can you replace a character in a string in Java?
In Java, you can use the replace method to substitute a character in a string. This 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:
String str = "Hello World!";
String newStr = str.replace('o', 'x');
System.out.println(newStr); // 输出:Hellx Wxrld!
In the example above, we replaced all instances of the character ‘o’ with ‘x’ in the string “Hello World!”, stored the result in the variable newStr, and finally printed the result to the console using the System.out.println method.
It is important to note that the replace method returns a new string and does not change the original string. If you want to replace within the original string, you can directly assign the result to the original string variable as shown below:
String str = "Hello World!";
str = str.replace('o', 'x');
System.out.println(str); // 输出:Hellx Wxrld!