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:

a

Enter the character to replace:

o

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

1
Sree On

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

Scanner myObj = new Scanner(System.in);  // 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 https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Other ways to read input from command line :

BufferedReader reader =  new BufferedReader(new InputStreamReader(System.in));

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

1
Dog Lover On

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

Scanner readInput = new Scanner(System.in);
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";
}