import java.util.*;
class App {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String: ");
String string = in.nextLine().toLowerCase();
System.out.print("Enter character to find: ");
String characterFind = in.nextLine().toLowerCase();
int index = string.indexOf(characterFind);
System.out.print("Index Position: ");
while (index >= 0) {
System.out.print(index + " ");
index = string.indexOf(characterFind, index + 1);
}
in.close();
}
}
Do this coding without using characterFind
import java.util.ArrayList;
import java.util.Scanner;
public class App{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String line = in.nextLine().toLowerCase();
System.out.print("Enter character to find: ");
char toFind = in.nextLine().toLowerCase().toCharArray()[0];
ArrayList<Integer> indexes = new ArrayList<>();
for (int i = 0; i < line.length(); i = index + 1) {
int index = line.indexOf(toFind, i);
if (index == -1) {
break;
}
indexes.add(index);
}
System.out.print("Index Position: ");
for (Integer index : indexes) {
System.out.print(index + " ");
}
System.out.println();
}
}
Comments
Leave a comment