how to replace a character with another character in a string in java

‮tth‬ps://www.lautturi.com
how to replace a character with another character in a string in java

To replace a character with another character in a String in Java, you can use the replace method of the String class. This method returns a new String object with all occurrences of the specified character replaced by the replacement character.

Here is an example of how you can use the replace method to replace a character with another character in a String in Java:

String str = "Hello, world!";
String replaced = str.replace('l', 'L');

System.out.println(replaced);  // Outputs "HeLLo, worLd!"

In this example, the replace method is called on the strString object, and it replaces all occurrences of the character 'l' with the character 'L' in the string. The result is a new String object with the modified string, which is stored in the replaced variable.

Keep in mind that the replace method operates on the original String object and creates a new String object with the modified string, without modifying the original String. If you want to modify the original String object, you can use the replace method of the StringBuilder class, which allows you to modify a String in place.

For example:

StringBuilder sb = new StringBuilder("Hello, world!");
sb.replace(2, 3, "LL");

System.out.println(sb);  // Outputs "HeLLo, world!"

In this example, the replace method of the StringBuilder class is called on the sbStringBuilder object, and it replaces the character at index 2 with the characters "LL" in the string. The result is a modified StringBuilder object with the modified string.

You can also use the replaceAll method of the String class, which allows you to replace all occurrences of a regular expression with a replacement string. This can be useful if you want to replace multiple characters or patterns in a String.

For example:

String str = "Hello, world!";
String replaced = str.replaceAll("[lL]", "X");

System.out.println(replaced);  // Outputs "HeXXo, worXd!"

In this example, the replaceAll method is called on the strString object, and it replaces all occurrences of the characters 'l' and 'L' with the character 'X' in the string. The result is a new String object with the modified string, which is stored in the replaced variable.

Created Time:2017-11-01 20:42:59  Author:lautturi