Answer to Question #160693 in Java | JSP | JSF for candice

Question #160693

Write a Java program to find a certain character in a string and replace it with a new character. Allow user to enter a string, find character and the replace character. Display the new string.


1
Expert's answer
2021-02-05T08:07:34-0500
import java.util.Scanner;

public class FindAndReplaceCharacter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String baseString = scanner.nextLine();
        System.out.print("Enter a character to find in the string: ");
        char foundCharacter = scanner.nextLine().charAt(0);
        System.out.println("Your character is found " + (baseString.length() - baseString.replaceAll(Character.toString(foundCharacter),"").length()) + " times");
        System.out.print("Enter a character to replace in the string: ");
        char replaceCharacter = scanner.nextLine().charAt(0);
        System.out.println("The string with the replaced character: " + baseString.replace(foundCharacter, replaceCharacter));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog