2012-12-19 60 views
8

可能重複:
Occurences of substring in a string一個字符串多少次包含另一個

如在本如何檢查一個串多少次包含另一個呢? 例子:

s1 "babab" 
s2 "bab" 
Result : 2 

如果我使用匹配器它只能識別第一次出現:

String s1 = JOptionPane.showInputDialog(" "); 
String s2 = JOptionPane.showInputDialog(" "); 
Pattern p = Pattern.compile(s2); 
Matcher m = p.matcher(s1); 
int counter = 0; 
while(m.find()){ 
    System.out.println(m.group()); 
    counter++; 
} 
System.out.println(counter); 

我能做到這樣,但我想下面使用Java庫就像和掃描儀,StringTokenizer的,匹配等:

String s1 = JOptionPane.showInputDialog(" "); 
String s2 = JOptionPane.showInputDialog(" "); 
String pom; 
int count = 0; 
for(int i = 0 ; i< s1.length() ; i++){ 
    if(s1.charAt(i) == s2.charAt(0)){ 
     if(i + s2.length() <= s1.length()){ 
      pom = s1.substring(i,i+s2.length()); 
      if(pom.equals(s2)){ 
       count++; 
      } 
     } 
    } 
} 

System.out.println(count); 
+0

這是一個家庭作業嗎? –

+3

您可以簡單地在最後找到的索引開始的while循環中使用'String#indexOf()'。 – assylias

+1

http://stackoverflow.com/questions/767759/occurences-of-substring-in-a-string –

回答

0

一些快速布魯斯·福特的解決方案:

String someString = "bababab"; 
    String toLookFor = "bab"; 
    int count = 0; 
    for (int i = 0; i < someString.length(); i++) { 
     if (someString.length() - i >= toLookFor.length()) { 
      if (someString.substring(i, i + toLookFor.length()).equals(toLookFor) && !"".equals(toLookFor)) { 
       count++; 
      } 
     } 
    } 
    System.out.println(count); 

這打印出3. 請注意我認爲String s都不爲空。

1

Matcher有兩種方法「start」和「end」,它們返回最後匹配的開始索引和結束索引。此外,方法find具有可選參數「開始」,開始搜索。

2

我認爲這可能會工作,如果你知道你正在尋找字符串,你可能需要編輯正則表達式模式tho。

String string = "hellohellohellohellohellohello"; 
Pattern pattern = Pattern.compile("hello"); 
Matcher matcher = pattern.matcher(string); 
int count = 0; 
while (matcher.find()) count++; 
+0

對於模式爲bab的字符串'babab',計數爲1。 – mtk

+0

你可以運行它爲「bababab」,並看到結果?如果它是兩個,那麼這些模式會丟棄它已經找到的那部分字符串。 我認爲它所做的是「bab-ab」有一個,所以這可能不是最適合你的。 – Drakoumel

+0

也許這會工作得更好(沒有測試過它,並寫在記事本中,所以要小心:D) String text =「babab」; String matchWord =「bab」; String newWord =「」; char [] chars = text.split(「」); int counter; 對(INT J = 0;Ĵ Drakoumel

0

,你可以不喜歡它的lulz

longStr

private int counterString(String s,String search) { 
    int times = 0; 
    int index = s.indexOf(search,0); 
    while(index > 0) { 
     index = s.indexOf(search,index+1); 
     ++times; 
    } 
    return times; 
} 
4

一個襯墊的解決方案是輸入字符串。 findStr是要搜索的字符串。沒有任何假設,但longStrfindStr必須nullfindStr必須至少有1個字符。只要

longStr.length() - longStr.replaceAll(Pattern.quote(findStr.substring(0,1)) + "(?=" + Pattern.quote(findStr.substring(1)) + ")", "").length() 

由於2場比賽被認爲是不同的,因爲他們開始不同的指數,和重疊的可能發生,我們需要一種方式比賽之間進行區分,並且允許匹配部分重疊。

訣竅是隻使用搜索字符串的第一個字符,並使用預見來斷言搜索字符串的其餘部分。這允許重疊部分被重新匹配,並且通過移除匹配的第一個字符,我們可以計算匹配的數量。

+0

這是如何工作的?我不明白Pattern.quote方法什麼是文字正則表達式? – MOnasz

+0

@ user1915933:這意味着即使字符串包含可以被識別爲正則表達式的字符或序列,它們也會被中和爲普通字符。 – nhahtdh

相關問題