Java String n-th index of a substring
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String str = "demo2s.com demo"; String searchStr = "mo"; int ordinal = 2; System.out.println(ordinalIndexOf(str, searchStr, ordinal)); }//from w w w. j av a 2 s. c o m /** * Represents a failed index search. * @since 2.1 */ public static final int INDEX_NOT_FOUND = -1; /** * <p>Finds the n-th index within a String, handling <code>null</code>. * This method uses {@link String#indexOf(String)}.</p> * * <p>A <code>null</code> String will return <code>-1</code>.</p> * * <pre> * ordinalIndexOf(null, *, *) = -1 * ordinalIndexOf(*, null, *) = -1 * ordinalIndexOf("", "", *) = 0 * ordinalIndexOf("aabaabaa", "a", 1) = 0 * ordinalIndexOf("aabaabaa", "a", 2) = 1 * ordinalIndexOf("aabaabaa", "b", 1) = 2 * ordinalIndexOf("aabaabaa", "b", 2) = 5 * ordinalIndexOf("aabaabaa", "ab", 1) = 1 * ordinalIndexOf("aabaabaa", "ab", 2) = 4 * ordinalIndexOf("aabaabaa", "", 1) = 0 * ordinalIndexOf("aabaabaa", "", 2) = 0 * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param ordinal the n-th <code>searchStr</code> to find * @return the n-th index of the search String, * <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input * @since 2.1 */ public static int ordinalIndexOf(String str, String searchStr, int ordinal) { if (str == null || searchStr == null || ordinal <= 0) { return INDEX_NOT_FOUND; } if (searchStr.length() == 0) { return 0; } int found = 0; int index = INDEX_NOT_FOUND; do { index = str.indexOf(searchStr, index + 1); if (index < 0) { return index; } found++; } while (found < ordinal); return index; } } /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */