Last active
August 29, 2015 14:03
-
-
Save Tomalak/31c1c55c1c79430be5c7 to your computer and use it in GitHub Desktop.
Alternative version of my answer in http://stackoverflow.com/questions/24674318/efficient-regular-expression-for-big-data-if-a-string-contains-a-word
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
public class IndexOfWord { | |
public static void main(String[] args) { | |
String input = "There are longer strings than this not very long one."; | |
String search = "long"; | |
// using a StringBuilder enables passing a string as | |
// a function argument without creating a copy of it | |
int index = indexOfWord(new StringBuilder(input), search); | |
if (index > -1) { | |
System.out.println("Hit for \"" + search + "\" at position " + index + "."); | |
} else { | |
System.out.println("No hit for \"" + search + "\"."); | |
} | |
} | |
public static int indexOfWord(StringBuilder input, String word) { | |
int index, before_i, after_i = 0; | |
while (true) { | |
index = input.indexOf(word, after_i); | |
if (index == -1 || word.isEmpty()) break; | |
before_i = index - 1; | |
after_i = index + word.length(); | |
if (isNonWord(input, before_i) && isNonWord(input, after_i)) { | |
return index; | |
} | |
} | |
return -1; | |
} | |
private static boolean isNonWord(StringBuilder input, int index) { | |
if (index < 0 || index > input.length() - 1) { | |
return true; | |
} else { | |
char c = input.charAt(index); | |
return !Character.isAlphabetic(c); // add more checks, as needed | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment