Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many times one string contains another [duplicate]

Tags:

java

string

regex

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);
like image 772
MOnasz Avatar asked Dec 19 '12 13:12

MOnasz


2 Answers

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.

like image 193
nhahtdh Avatar answered Nov 02 '22 01:11

nhahtdh


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++;
like image 2
czioutas Avatar answered Nov 02 '22 02:11

czioutas