Skip to content
Advertisement

Print index position of letter from sentence using JOptionPane

I need to ask the user to input a sentence and then a letter. The program should then print out how many letters the sentence contains. Also the index position of the specified character that the user inputted. My problem is that I don’t know how to find the position of that character.

NOTE: I have searched the web for answer.

JavaScript

Advertisement

Answer

If you want to show just the first index where the character is found, you can use String#indexOf(int ch). If you want to display all the positions where the letter occurs in the sentence, you can use String#indexOf(String str, int fromIndex).

Demo:

JavaScript

Output:

JavaScript

Alternatively, you can use String#charAt:

JavaScript

Output:

JavaScript

You can also add all the positions to a List<Integer> and display the same.

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement