Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Single word:</h1> <p>You can achiveve that using <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29" rel="noreferrer"><code>String</code>'s <code>split()</code> method</a>. This solution is <strong>O(n)</strong>.</p> <pre><code>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 &lt; sp.length; i++) { if (sp[i].equals(find)) { // have to check for ArrayIndexOutOfBoundsException String surr = (i-2 &gt; 0 ? sp[i-2]+" " : "") + (i-1 &gt; 0 ? sp[i-1]+" " : "") + sp[i] + (i+1 &lt; sp.length ? " "+sp[i+1] : "") + (i+2 &lt; sp.length ? " "+sp[i+2] : ""); System.out.println(surr); } } } </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>John and I like to and hiking I have two </code></pre> <h1>Multi-word:</h1> <p>Regex is a great and clean solution for case when <code>find</code> is a multi-word. Due to its nature, though, it misses the cases when the <strong>the words around also match <code>find</code></strong> (see the an example of this below).</p> <p>The algorithm below takes care of all cases (all solutions' space). Bear in mind that, due to the nature of the problem, this solution in the worst case is <strong>O(n*m)</strong> <sup>(with <code>n</code> being <code>str</code>'s length and <code>m</code> being <code>find</code>'s length)</sup>.</p> <pre><code>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 &lt; sp.length; i++) { int j = 0; while (j &lt; spMulti.length &amp;&amp; i+j &lt; sp.length &amp;&amp; sp[i+j].equals(spMulti[j])) { j++; } if (j == spMulti.length) { // found spMulti entirely StringBuilder surr = new StringBuilder(); if (i-2 &gt; 0){ surr.append(sp[i-2]); surr.append(" "); } if (i-1 &gt; 0){ surr.append(sp[i-1]); surr.append(" "); } for (int k = 0; k &lt; spMulti.length; k++) { if (k &gt; 0){ surr.append(" "); } surr.append(sp[i+k]); } if (i+spMulti.length &lt; sp.length) { surr.append(" "); surr.append(sp[i+spMulti.length]); } if (i+spMulti.length+1 &lt; sp.length) { surr.append(" "); surr.append(sp[i+spMulti.length+1]); } System.out.println(surr.toString()); } } } </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>name is John and John and John and John and I like </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload