Write a program to take a String as input then display the position of a particular character given as input using indexOf() function of String class. Don't use charAt() function.
Enter a String
Elephants are the largest mammals
Enter character to find: e
Index Position: 0 2 12 16 22
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String line = in.nextLine();
System.out.print("Enter character to find: ");
String toFind = in.nextLine();
ArrayList<Integer> indexes = new ArrayList<>();
for (int i = 0; i < line.length(); ) {
int index = line.toLowerCase().indexOf(toFind.toLowerCase().toCharArray()[0], i);
if (index == -1) {
break;
}
i = index + 1;
indexes.add(index);
}
System.out.print("Index Position: ");
for (Integer index : indexes) {
System.out.print(index + " ");
}
System.out.println();
}
}
Comments
Leave a comment