Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In the general case, this method works. It surrounds the earliest substring of any keyword in any given String:</p> <pre><code>public String bracketize() { String chars = ...; // you can put whatever input (such as 'these are some chars *£&amp;$') String keyword = ...; // you can put whatever keyword (such as *£&amp;$^%) String longest = ""; for(int i=0;i&lt;keyword.length()-1;i++) { for(int j=keyword.length(); j&gt;i; j--) { String tempString = keyword.substring(i,j); if(chars.indexOf(tempString) != -1 &amp;&amp; tempString.length()&gt;longest.length()) { longest = tempString; } } } if(longest.length() == 0) return chars; // no possible substring of keyword exists in chars, so just return chars String bracketized = chars.substring(0,chars.indexOf(longest))+"("+longest+")"+chars.substring(chars.indexOf(longest)+longest.length()); return bracketized; } </code></pre> <p>The nested <code>for</code> loops check every possible substring of <code>keyword</code> and select the longest one that is contained in the bigger <code>String</code>, <code>chars</code>. For example, if the keyword is Dog, it will check the substrings "Dog", "Do", "D", "og", "o", and "g". It stores this longest possible substring in <code>longest</code> (which is initialized to the empty String). If the length of <code>longest</code> is still 0 after checking every substring, then no such substring of <code>keyword</code> can be found in <code>chars</code>, so the original String, chars, is returned. Otherwise, a new string is returned which is <code>chars</code> with the substring <code>longest</code> surrounded by brackets (parentheses).</p> <p>Hope this helps, let me know if it works.</p>
 

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