Skip to content

Instantly share code, notes, and snippets.

@syhily
Last active February 12, 2016 12:02
Show Gist options
  • Select an option

  • Save syhily/11a8f4e47483fb950818 to your computer and use it in GitHub Desktop.

Select an option

Save syhily/11a8f4e47483fb950818 to your computer and use it in GitHub Desktop.
在Java语言中,怎么样查找一个特定的字符串,获取它的下一个索引位置,并返回它的索引位置? 例如说:我要在一组字符串中查找一个子字符串"activity",要求返回它的索引位置,同时,这个字符在字符串中出现的次数至少多于2次,也就是说,我需要一个方法能够直接获取它在字符串中出现的各个索引!
import com.google.common.collect.Lists;
import java.util.List;
/**
* Title: StringMatchUtil
* Description:
*
* @author Yufan
* @version 1.0.0
* @since 2016-02-12 18:00
*/
public class StringMatchUtil {
private StringMatchUtil() {
// No Construct
}
public static List<Integer> match(String str, String matchStr) {
return strMatch(str, matchStr, str.indexOf(matchStr), new ArrayList<Integer>());
}
private static List<Integer> strMatch(String str, String matchStr, int offset, List<Integer> index) {
if (offset >= 0) {
index.add(offset);
return strMatch(str, matchStr, str.indexOf(matchStr, offset + 1), index);
}
return index;
}
public static void main(String[] args) {
String str = "AAAAAAAAAA";
String matchStr = "A";
List<Integer> result = match(str, matchStr);
System.out.print(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment