I have large String variable named text. I want to be able to check if text contains a specified searchString (e.g. “test”) and to return all substrings with windowSize chars before and after the matches.
Example:
String windowSize = 5;
String text = "this is only a simple test. lorem impsum testing everything.";
String searchString = "test";
As a result i want the following output:
mple test. lor
ssum testing e
Additionally, it would be great to be able to have different types of output:
Only before:
mple
ssum
Only after:
. lor
ing e
Solution
Thanks to Peter Lawrey and SubmittedDenied i got my answer:
String windowSize = 5;
String text = "this is only a simple test. lorem impsum testing everything.";
String searchString = "test";
int i = -1;
while((i = text.indexOf(searchString, i+1)) > -1) {
System.out.println(text.substring(Math.max(0, i - windowSize), Math.min(i + searchString.length() + windowSize, text.length())));
}
You can find the location of a substring with the
indexOf(string)method, this will also return-1if there is no such substring.You’d want to do something like:
You’ll probably need to catch errors like if the first occurence of
testis less thanwindowSizecharacters into the string.