Here you can find the source of findAllOccurrences(String str, String substr)
Parameter | Description |
---|---|
str | the string to search |
substr | the substring to search for |
public static int[] findAllOccurrences(String str, String substr)
//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; } }