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

Similar Programs Chapter Last Updated
How To Check If A String Contains A Particular Substring In Java String Handling 22-08-2023
How To Split A String Into Substrings in Java String Handling 22-08-2023
How To Remove A Substring From A String Java String Handling 22-08-2023
Java Program To Remove Repeated Characters In A String String Handling 15-08-2023
Java Code To Check If String Contains Specific Characters String Handling 03-06-2023
How To Count The Number Of Cccurrences Of Each Character In A String In Java String Handling 03-06-2023
Java Program To Split A String String Handling 03-06-2023
String Length Implementation Java String Handling 02-12-2019

1