w3resource

Java: Replace a specified character with another character


24. Replace Character

Write a Java program to replace a specified character with another character.

Visual Presentation:

Java String Exercises: Replace a specified character with another character


Sample Solution:

Java Code:

// Define a public class named Exercise24.
public class Exercise24 {
    
    // Define the main method.
    public static void main(String[] args) {
        // Declare and initialize a string variable.
        String str = "The quick brown fox jumps over the lazy dog.";

        // Replace all the 'd' characters with 'f' characters.
        String new_str = str.replace('d', 'f');

        // Display the original and modified strings for comparison.
        System.out.println("Original string: " + str);
        System.out.println("New String: " + new_str);
    }
}

Sample Output:

Original string: The quick brown fox jumps over the lazy dog.                                                 
New String: The quick brown fox jumps over the lazy fog.

Flowchart:

Flowchart: Java String  Exercises - Replace a specified character with another character


For more Practice: Solve these Related Problems:

  • Write a Java program to replace all occurrences of a specific character in a string with another character.
  • Write a Java program to replace only the first and last occurrence of a character in a string.
  • Write a Java program to replace every vowel in a string with a star (*) symbol.
  • Write a Java program to substitute all instances of a given character in a string while preserving the original case.

Go to:


PREV : Region Match Between Strings.
NEXT : Replace Substring with Regex.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.