Write a program in JAVA to enter a sentence from the keyboard and search for a character in it and print the locations at which the character is present in the string.
E.g.: Venkatesh is playing with a kite.
Enter the character to be searched: k
Output: Searched character found at location(s): 4 29
Answers
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
Sample input 2:
Enter the string:
java programming
Enter the character to be searched:
e
Enter the character to replace:
o
Sample output 2:
character not found
Program to get input from keyboard, search a character and print the location:
import java.util.Scanner;
public class PrintStringChars1 {
private static Scanner sc;
public static void main(String[] args) {
String str;
int i;
sc= new Scanner(System.in);
System.out.print("\n Please Enter any String to Print = ");
str = sc.nextLine();
for(i = 0; i < str.length(); i++)
{
System.out.println("The Character at Position " + i + " = " + str.charAt(i));
}
}
}