Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It is similar to search a subString in a String. </p> <p>e.g. </p> <pre><code>A B C D N E X T J H J N E N E X T O 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 </code></pre> <p>So the answer should be <code>[4-7]</code> and <code>[13-16]</code>.</p> <pre><code>public static List&lt;Integer&gt; findIndexes(String source, String toFind){ List&lt;Integer&gt; list = new LinkedList&lt;Integer&gt;();//it will return the starting indexes of the found substring, we can easily find the end e=index by adding the length of the other. int start = 0; while(start &lt; source.length()){ if(source.charAt(start)==toFind.charAt(0)){//if the char is same then find whether the whole toFind string is present or not. if(isMatch(source, toFind, start)){//if it is found than increment the source pointer to the end after the toFind string list.add(start); start = start+toFind.length(); continue; } } start++; } return list; } private static boolean isMatch(String s1, String s2, int srcIndex){ int desIndex = 0; while(desIndex&lt;s2.length() &amp;&amp; s1.charAt(srcIndex)==s2.charAt(desIndex)){ srcIndex++; desIndex++; } if(desIndex==s2.length()){ return true; } return false; } </code></pre> <p>And sample driver program:</p> <pre><code>public static void main(String[] args) { String s1="abcdnextponexnextpour"; String s2 = "next"; List&lt;Integer&gt; list = findIndexes(s1, s2); for(int i : list){ System.out.println(i); } } </code></pre> <p>It will output the indexes:</p> <pre><code>4 13 </code></pre> <p>i.e. you can add the length of the <code>toFind</code> String to calculate the last index.</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