Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.
wordEnds("abcXY123XYijk", "XY") → "c13i"
wordEnds("XY123XY", "XY") → "13"
wordEnds("XY1XY", "XY") → "11"
Source
public String wordEnds(String str, String word) {if(str.indexOf(word)==-1 | str.equals(word)) return "";String ends="";for(int i=0 ; i<str.length() ; i++){i=str.indexOf(word, i);if(i==0) { // in the beginingends+=""+str.charAt(i+word.length());i=i+word.length()-1;}else if(i==str.length()-word.length()){ // in the endends+=""+str.charAt(i-1);break;}else if(i==-1) break; // no more matcheselse{ // in the middleends+=""+str.charAt(i-1)+str.charAt(i+word.length());i=i+word.length()-1;}}return ends;}