Java program to find a character from a sentence and replace it with another character. If the character is not found in the string print "character not found".

Note: Replace only the first occurrence.

Sample input 1:

Enter the string:

java programming

Enter the character to be searched:


Enter the character to replace:


Sample output 1:

jova programming

Kindly suggest me how to take user input for the character to be replaced and replace the character.

2 Answers

Sree On

In general to get a input from user you could a scanner class.

Scanner myObj = new Scanner(;  // Create a Scanner object
System.out.println("Enter the character to be searched");
String characterToReplace = myObj.nextLine();  // Read user input

System.out.println("Enter the character to replace");
String replacementCharacter = myObj.nextLine();

Information on scanner class

Other ways to read input from command line :

BufferedReader reader =  new BufferedReader(new InputStreamReader(;

For replacing a character you could just string.replace method to perform the required operations.

Dog Lover On

You can achieve this by putting this code in a function:

Scanner readInput = new Scanner(;
System.out.println("Enter the string to search:");
String search = readInput.nextLine();
System.out.println("Enter the character to be searched:");
String find = readInput.nextLine();
System.out.println("Enter the character to replace it with:");
String replace = readInput.nextLine();
if (search.contains(find)) {
    return search.replaceFirst(find, replace);
} else {
    return "Character not found";