find substring algorithm java

Brute-force algorithm
   @searchTarget The substring to be searched
   @searchFrom Find the source
    public ArrayList<Integer> search(String searchTarget, String searchFrom) {
        //There may be multiple substrings to be found, strPos records the position of the substring
        ArrayList<Integer> strPos = new ArrayList<Integer>();
        int targetLen = searchTarget.length();
        int fromLen = searchFrom.length();

        // use j to traverse the searched substring
        int j = 0;

        // use i to traverse all Substring
           for(int i = 0; i < fromLen - targetLen; i++) {

            // Match in sequence, one character by one character // If the match is successful, return the value of i
            for(j = 0; j < targetLen; j++) {
                if (searchFrom.charAt(i+j) != searchTarget.charAt(j)) {
                    break;
                }
            }
            //If the searched substring is traversed to the end, the matching target is found
            if (j == targetLen) {
                strPos.add(i);
                i=i+M
            }
        }
        return strPos;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326239040&siteId=291194637