How to get the indexes of words from an array of strings that start with a specific letter in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

public class WordIndexFinder {
    public static void main(String[] args) {
        String[] words = {"zero", "one", "two", "three", "four", "five", 
                          "six", "seven", "eight", "nine", "ten"};
        char targetLetter = 't';
        
        List<Integer> indexes = getIndexesOfWordsStartingWith(words, targetLetter);
        
        System.out.println("Indexes of words starting with '" + targetLetter + "': " + indexes);
    }

    public static List<Integer> getIndexesOfWordsStartingWith(String[] words, char letter) {
        List<Integer> indexes = new ArrayList<>();
        int words_length = words.length;
        
        for (int i = 0; i < words_length; i++) {
            if (words[i].toLowerCase().charAt(0) == letter) {
                indexes.add(i);
            }
        }
        
        return indexes;
    }
}



/*
run:

Indexes of words starting with 't': [2, 3, 10]

*/

 



answered Mar 14, 2025 by avibootz
...