Java String Find findAllOccurrences(String str, String substr)

Here you can find the source of findAllOccurrences(String str, String substr)

Description

Returns an array of integers listing the beginning indices of each occurrence of the substring in the given string.

License

Open Source License

Parameter

Parameter Description
str the string to search
substr the substring to search for

Declaration

public static int[] findAllOccurrences(String str, String substr) 

Method Source Code


//package com.java2s;
/* This file is part of Green.
 *
 * Copyright (C) 2005 The Research Foundation of State University of New York
 * All Rights Under Copyright Reserved, The Research Foundation of S.U.N.Y.
 * /* w  w w.ja  v  a2s. co  m*/
 * Green is free software, licensed under the terms of the Eclipse
 * Public License, version 1.0.  The license is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.util.ArrayList;

public class Main {
    /**
     * Returns an array of integers listing the beginning indices of each
     * occurrence of the substring in the given string.  A zero length array is returned
     * if the specified substring is not found.
     *  
     * @param str the string to search
     * @param substr the substring to search for
     * @return
     */
    public static int[] findAllOccurrences(String str, String substr) {
        if (str.indexOf(substr) == -1) {
            return new int[] {};
        }

        ArrayList<Integer> indexList = new ArrayList<Integer>();
        String tempStr = str;
        int prevAbsoluteIndex = 0;
        while (tempStr.indexOf(substr) != -1) {
            int index = tempStr.indexOf(substr);
            indexList.add(new Integer(prevAbsoluteIndex + index));
            tempStr = tempStr.substring(index + 1);
            prevAbsoluteIndex += index + 1;
        }
        int[] indices = new int[indexList.size()];
        for (int i = 0; i < indexList.size(); i++) {
            indices[i] = indexList.get(i);
        }
        return indices;
    }
}

Related

  1. findAll(final String s, final String subs)
  2. findAll(String toSearch, String toFind, boolean ignoreCase)
  3. findAllIndexes(String str, String searchStr)
  4. findAllOccurences(String str, String pattern)
  5. findAllSubsequences(String str)
  6. findParam(String src, char patternFrom, char patternTo)
  7. findResourceBundle(String aBundleName, Locale locale)
  8. getAllOccurences(String str, char guess)