How to find the start index of all matches of a word in a string with Java

2 Answers

0 votes
public class Program {

    public static void main(String[] args) {
        String s = "Java programming language, java object-oriented, java class-base";
        String word = "java";

        findOccurrences(s, word);
    }

    public static void findOccurrences(String text, String word) {
        for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
            System.out.println(i);
        }
    }
}


/*
run:

27
49

*/

 



answered Apr 27, 2019 by avibootz
edited Aug 29 by avibootz
0 votes
public class Program {

    public static void main(String[] args) {
        String s = "Java programming language, java object-oriented, java class-base";
        String word = "java";

        findOccurrencesIgnoreCase(s, word);
    }

    public static void findOccurrencesIgnoreCase(String text, String word) {
        String lowerText = text.toLowerCase();
        String lowerWord = word.toLowerCase();

        for (int i = -1; (i = lowerText.indexOf(lowerWord, i + 1)) != -1; i++) {
            System.out.println(i);
        }
    }
}


/*
run:

0
27
49

*/

 



answered Apr 27, 2019 by avibootz
edited Aug 29 by avibootz
...