8

Possible Duplicate:
Occurences of substring in a string

As in the subject how to check how many times one string contains another one? Example:

s1 "babab"
s2 "bab" 
Result : 2

If i use Matcher it does only recognize first occurence:

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);

I can do it like that, but I would like below to use Java libraries iike Scanner, StringTokenizer, Matcher etc:

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);
Community
  • 1
  • 1
MOnasz
  • 99
  • 1
  • 2
  • 8

5 Answers5

4

One liner solution for the lulz

longStr is the input string. findStr is the string to search for. No assumption, except that longStr and findStr must not be null and findStr must have at least 1 character.

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

Since 2 matches are considered different as long as they starts at different index, and overlapping can happen, we need a way to differentiate between the matches and allow for matched part to be overlapped.

The trick is to consume only the first character of the search string, and use look-ahead to assert the rest of the search string. This allows overlapping portion to be rematched, and by removing the first character of the match, we can count the number of matches.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
  • How this works? I don't understand the Pattern.quote method what is literal regex? – MOnasz Dec 19 '12 at 14:09
  • @user1915933: It means that even if the string contains characters or sequences that can be recognized as regex, those will be neutralized into normal characters. – nhahtdh Dec 19 '12 at 14:11
2

i think this might work if you know the word you are looking for in the string you might need to edit the regex pattern tho.

String string = "hellohellohellohellohellohello";
Pattern pattern = Pattern.compile("hello"); 
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) count++;
czioutas
  • 1,032
  • 2
  • 11
  • 37
  • For string `babab` with pattern `bab` gives count as `1`. – mtk Dec 19 '12 at 13:43
  • could you run it for "bababab" and see the result? if it is two then the patterns discards the part of the string that it already found one. I think what it does is "bab-ab" there is one, so this might not be the best for you.. – czioutas Dec 19 '12 at 13:45
  • maybe this would work better (havent tested it and wrote it in notepad so be carefull :D ) String text = "babab"; String matchWord = "bab"; String newWord = ""; char[] chars = text.split(""); int counter; for(int j=0; j – czioutas Dec 19 '12 at 13:52
1

The class Matcher has two methods "start" and "end" which return the start index and end index of the last match. Further, the method find has an optional parameter "start" at which it starts searching.

Philipp
  • 67,764
  • 9
  • 118
  • 153
1

you can do it like this

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;
 }
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
0

Some quick Bruce Forte solution:

    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);

This prints out 3. Please note I assume that none of the Strings is null.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207