I want to get the string between 2 words in a string. like so:
String s = "Play A ROCK song"
So I want to get the string between: A and song, which in this case is rock.
I tried this:
public static String subStringBetween(String text, String after, String before) {
String p1 = getWordsAfter(text, after);
String p2 = getWordsBefore(text, before);
Set<String> aSet = new HashSet<>(Arrays.asList(p1.split(" ")));
Set<String> bSet = new HashSet<>(Arrays.asList(p2.split(" ")));
Set<String> result = new HashSet<>(aSet);
result.retainAll( bSet);
String string = "";
for (String s : result) {
if (string == "") {
string = s;
}else{
string +=" " + s;
}
}
return string;
}
public static String getWordsAfter(String text, String word) {
String[] splt = text.split(word);
return splt[1];
}
public static String getWordsBefore(String text, String word) {
String[] splt = text.split(word);
return splt[0];
}
It works, but If the string between A and Song is more than one word, it works, but prints something weird, like if it was: Play a Nice Rock Song the return would be Rock Nice, not Nice Rock