2015-09-25 113 views
6

我試圖在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://stackoverflow.com/questions/767759/occurrences-of-substring-in-a-string)可以幫助你。爲了獲取索引,只要在接收到索引時打印或保存'lastIndex'。 –

+2

你的意思是你需要[像這樣的東西](http://ideone.com/9IeCEQ)? –

+1

請使用更有意義的變量名稱。很難理解「cthing1」或「outthing」或「niwords」的含義。使用'lastIndex','indexList'等東西可以讓你更容易理解你寫的東西並改正它。 – RealSkeptic

回答

5

你可以用一個積極的前瞻中捕獲得到所有重疊的匹配,並使用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

0

使用正則表達式肯定是找到子字符串的過於繁重的解決方案,如果您的子字符串包含像.這樣的特殊正則字符,它尤其會成爲一個問題。下面是改編自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

你是對的,忘記了重疊部分。編輯。 –

相關問題