Skip to content

Instantly share code, notes, and snippets.

@Tomalak
Last active August 29, 2015 14:03
Show Gist options
  • Save Tomalak/31c1c55c1c79430be5c7 to your computer and use it in GitHub Desktop.
Save Tomalak/31c1c55c1c79430be5c7 to your computer and use it in GitHub Desktop.
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