我試圖在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中實現這一點?
我想頂帖[這裏](http://stackoverflow.com/questions/767759/occurrences-of-substring-in-a-string)可以幫助你。爲了獲取索引,只要在接收到索引時打印或保存'lastIndex'。 –
你的意思是你需要[像這樣的東西](http://ideone.com/9IeCEQ)? –
請使用更有意義的變量名稱。很難理解「cthing1」或「outthing」或「niwords」的含義。使用'lastIndex','indexList'等東西可以讓你更容易理解你寫的東西並改正它。 – RealSkeptic