Created
September 12, 2018 14:49
-
-
Save SubhamTyagi/28afed0715271fe2fbbb5a171bccbde3 to your computer and use it in GitHub Desktop.
This example is used to show the difference between 'regex search' and 'use of indexOf'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class FindingFullWord { | |
public static void main(String[] args) { | |
String sentence="dia India dia dialog fadia dia"; | |
String word="dia"; | |
System.out.println("count by first method =="+simpleCount(word,sentence));//count by first method ==6 | |
System.out.println("count by second method =="+regexCount(word,sentence));//count by second method ==3 | |
} | |
public static int simpleCount(String subString, String string) { | |
int lastIndex = 0; | |
int cnt = 0; | |
while (lastIndex != -1) { | |
lastIndex = string.indexOf(subString, lastIndex); | |
if (lastIndex != -1) { | |
cnt = cnt + 1; | |
lastIndex += subString.length(); | |
} | |
} | |
return cnt; | |
} | |
static int regexCount(String subString, String string) { | |
int cnt = 0; | |
String regex="\\b"+subString+"\\b"; | |
Pattern p = Pattern.compile(regex); | |
Matcher m = p.matcher(string); | |
while (m.find()) | |
cnt++; | |
return cnt; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment