查找在Java中的字符串中出现的所有子字符串

问题描述:

我试图在Java中查找字符串中的所有子字符串。查找在Java中的字符串中出现的所有子字符串

例如: 搜索“ababsdfasdfhelloasdf”为“ASDF”将返回[8,17],因为有2“ASDF”的,一个在位置8和一个在17处 搜索‘AAAAAA’为“AA “将返回[0,1,2,3,4],因为有一个 ”AA“ 在位置0,1,2,3和4

我尝试这样做:

public List<Integer> findSubstrings(String inwords, String inword) { 
    String copyOfWords = inwords; 
    List<Integer> indicesOfWord = new ArrayList<Integer>(); 
    int currentStartIndex = niwords.indexOf(inword); 
    int indexat = 0; 
    System.out.println(currentStartIndex); 
    while (cthing1 > 0) { 
     indicesOfWord.add(currentStartIndex+indexat); 
     System.out.println(currentStartIndex); 
     System.out.println(indicesOfWord); 
     indexat += cthing1; 
     copyOfWords = copyOfWords.substring(cthing1); 
     System.out.println(copyOfWords); 
     cthing1 = copyOfWords.indexOf(inword); 
    } 

这问题可以在Python可以解决如下:

indices = [m.start() for m in re.finditer(word, a.lower())] 

其中“单词”是我正在查找的单词,“a”是我正在搜索的字符串。

我该如何在Java中实现这一点?

+0

我想顶帖[这里](http://*.com/questions/767759/occurrences-of-substring-in-a-string)可以帮助你。为了获取索引,只要在接收到索引时打印或保存'lastIndex'。 –

+2

你的意思是你需要[像这样的东西](http://ideone.com/9IeCEQ)? –

+1

请使用更有意义的变量名称。很难理解“cthing1”或“outthing”或“niwords”的含义。使用'lastIndex','indexList'等东西可以让你更容易理解你写的东西并改正它。 – RealSkeptic

你可以用一个积极的前瞻中捕获得到所有重叠的匹配,并使用Matcher#start得到捕获的子串的索引。

至于the regex,它看起来像

(?=(aa)) 

在Java代码:

String s = "aaaaaa"; 
Matcher m = Pattern.compile("(?=(aa))").matcher(s); 
List<Integer> pos = new ArrayList<Integer>(); 
while (m.find()) 
{ 
    pos.add(m.start()); 
} 
System.out.println(pos); 

结果:

[0, 1, 2, 3, 4] 

IDEONE demo

使用正则表达式肯定是找到子字符串的过于繁重的解决方案,如果您的子字符串包含像.这样的特殊正则字符,它尤其会成为一个问题。下面是改编自this answer一个解决方案:

String str = "helloslkhellodjladfjhello"; 
String findStr = "hello"; 
int lastIndex = 0; 
List<Integer> result = new ArrayList<Integer>(); 

while(lastIndex != -1) { 

    lastIndex = str.indexOf(findStr,lastIndex); 

    if(lastIndex != -1){ 
     result.add(lastIndex); 
     lastIndex += 1; 
    } 
} 
+0

这会返回[0,2,4]作为海报想要的“aa”NOT [0,1,2,3,4]。需要仅通过1而不是findStr的长度来增加lastIndex来查找所有的子匹配。 – JasonM1

+0

你是对的,忘记了重叠部分。编辑。 –