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.
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));
}
}
Comments
Leave a comment