Java Program To Replace A Character In A String
Chapter:
String Handling
Last Updated:
03-06-2023 12:56:05 UTC
Program:
/* ............... START ............... */
public class CharacterReplacer {
public static void main(String[] args) {
String originalString = "Hello, World!";
char charToReplace = 'o';
char replacementChar = 'X';
String replacedString = replaceChar(originalString, charToReplace, replacementChar);
System.out.println("Replaced string: " + replacedString);
}
public static String replaceChar(String originalString, char charToReplace, char replacementChar) {
char[] charArray = originalString.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == charToReplace) {
charArray[i] = replacementChar;
}
}
return new String(charArray);
}
}
/* ............... END ............... */
Output
Replaced string: HellX, WXrld!
In this output, all occurrences of the character 'o' in the original string "Hello, World!" have been
replaced with 'X'.
Notes:
-
The program defines a replaceChar method that takes three arguments: the original string, the character to be replaced, and the replacement character. It converts the original string to a character array using toCharArray().
- The method iterates over each character in the character array using a for loop. If a character matches the one to be replaced, it replaces it with the replacement character by assigning the value to the corresponding index in the array.
- Finally, the modified character array is converted back to a string using the String(char[]) constructor and returned as the replaced string. In the main method, a sample input is provided where all occurrences of the character 'o' in the string "Hello, World!" are replaced with 'X'. The resulting replaced string is then printed to the console.
Tags
Java program to replace a character in a string #How do you replace a character with a string in Java? #Java String replace() method