How to find the first occurrence of a pattern in a string from some starting position in Java

1 Answer

0 votes
public class FindSubstring {
    public static void main(String[] args) {
        String str = "abcdefgaaahijklaaaamnopqaaaaarst";
        String pattern = "aaa";
        int startPosition = 11; // Starting position to search from

        // Find the first occurrence of the pattern starting from the given position
        int foundPosition = str.indexOf(pattern, startPosition);

        if (foundPosition != -1) {
            System.out.println("Pattern found at position: " + foundPosition);
        } else {
            System.out.println("Pattern not found!");
        }
    }
}



/*
run:

Pattern found at position: 15

*/

 



answered Jun 10, 2025 by avibootz
...