Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Not really very close, I'm afraid. What that code basically does is check there if the two strings have two characters in the same positions at any point and, if so, returns the index of the second of those characters. E.g., if <code>_str</code> is "abcdefg" and <code>str</code> is "12cd45", you'll return 3 because they have "cd" in the same place, and that's the index of the "d". At least, that's as near as I can tell what it's actually doing. That's because you're indexing into both strings with the same indexing variable.</p> <p>To re-write <code>indexOf</code>, looking for <code>str</code> within <code>_st</code>, you have to scan <code>_st</code> for the first character in <code>str</code> and then check whether the remaining characters match; if not, bump forward one place from where you started checking and continue your scan. (There are optimisations you can do, but that's the essence of it.) So for instance, if you find the first character of <code>str</code> at index 4 in <code>_st</code> and <code>str</code> is six characters long, having found the first character you need to see if the remaining five (<code>str</code>'s indexes 1-5 inclusive) match <code>_st</code>'s indexes 5-10 inclusive (easiest just to check all six of <code>str</code>'s characters against a substring of <code>_st</code> starting at 4 and going for six charactesr). If everything matches, return the index at which you found the first character (so, 4 in that example). You can stop scanning at <code>_st.length() - str.length()</code> since if you haven't found it starting prior to that point, you're not going to find it at all.</p> <p>Side point: Don't call the <code>length</code> function on every loop. The JIT <em>may</em> be able to optimize out the call, but if you know that <code>_st</code> won't change during the course of this function (and if you don't know that, you should require it), grab <code>length()</code> to a local and then refer to that. And of course, since you know you can stop earlier than <code>length()</code>, you'l use a local to remember where you can stop.</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