One word:
You can achieve using the String split() method. This solution is O (n) .
public static void main(String[] args) { String str = "Hello my name is John and I like to go fishing and "+ "hiking I have two sisters and one brother."; String find = "I"; String[] sp = str.split(" +"); // "+" for multiple spaces for (int i = 2; i < sp.length; i++) { if (sp[i].equals(find)) { // have to check for ArrayIndexOutOfBoundsException String surr = (i-2 > 0 ? sp[i-2]+" " : "") + (i-1 > 0 ? sp[i-1]+" " : "") + sp[i] + (i+1 < sp.length ? " "+sp[i+1] : "") + (i+2 < sp.length ? " "+sp[i+2] : ""); System.out.println(surr); } } }
Output:
John and I like to and hiking I have two
Multi-word:
Regex is a great and clean solution for the case where find is verbose. Due to its nature, it skips cases where the words around also match find (see the example below).
In the algorithm below, all cases are considered (the space of all solutions). Keep in mind that due to the nature of the problem, this solution is in the worst case O (n * m) (with n str and m length find ) .
public static void main(String[] args) { String str = "Hello my name is John and John and I like to go..."; String find = "John and"; String[] sp = str.split(" +"); // "+" for multiple spaces String[] spMulti = find.split(" +"); // "+" for multiple spaces for (int i = 2; i < sp.length; i++) { int j = 0; while (j < spMulti.length && i+j < sp.length && sp[i+j].equals(spMulti[j])) { j++; } if (j == spMulti.length) { // found spMulti entirely StringBuilder surr = new StringBuilder(); if (i-2 > 0){ surr.append(sp[i-2]); surr.append(" "); } if (i-1 > 0){ surr.append(sp[i-1]); surr.append(" "); } for (int k = 0; k < spMulti.length; k++) { if (k > 0){ surr.append(" "); } surr.append(sp[i+k]); } if (i+spMulti.length < sp.length) { surr.append(" "); surr.append(sp[i+spMulti.length]); } if (i+spMulti.length+1 < sp.length) { surr.append(" "); surr.append(sp[i+spMulti.length+1]); } System.out.println(surr.toString()); } } }
Output:
name is John and John and John and John and I like
acdcjunior
source share