Answer to Question #296591 in Java | JSP | JSF for Lener

Question #296591

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


1
Expert's answer
2022-02-11T17:23:46-0500
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();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS