Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In first, your code is broken. <code>size_t</code> is unsigned type and never can be <code>i&lt;0</code>.</p> <p>In second, your code is ugly std library misuse and ineffective. There should be used regular expression library or such or use handcrafted scanner. Resulting code is far cleaner and faster. For example (I have not been using C for many years but below code crafted in 10 minutes works.):</p> <pre><code>size_t findSlash(const char *sz, int i) { const char *s = sz; if (i&lt;0) { for(;*s;s++); for(;;s--){ if(s&lt;sz) return -1; if((*s == '/') || (*s == '\\')) if(! ++i) break; } } else { for(;;s++){ if(! *s) return -1; if((*s == '/') || (*s == '\\')) if(! i--) break; } } return s-sz; } </code></pre> <p>I haven't used to write Haskell or F# but for example below code in Erlang should state as example how to do it in functional language:</p> <pre><code>findslash(L, I) when is_list(L), is_integer(I) -&gt; if I&lt;0 -&gt; case findslash(lists:reverse(L), -1*I - 1, 0) of none -&gt; none; X -&gt; length(L) - X - 1 end; I&gt;=0 -&gt; findslash(L, I, 0) end. findslash([H|_], 0, X) when H=:=$/; H=:=$\\ -&gt; X; findslash([H|T], I, X) when H=:=$/; H=:=$\\ -&gt; findslash(T, I-1, X+1); findslash([_|T], I, X) -&gt; findslash(T, I, X+1); findslash([], _, _) -&gt; none. </code></pre> <p>My attempt in Haskell with error checking and keeps laziness for i>=0:</p> <pre><code>findSlash :: String -&gt; Int -&gt; Maybe Int findSlash str i | i &lt; 0 = reversed (_findSlash (reverse str) (-1*i-1) 0) | i &gt;= 0 = _findSlash str i 0 where reversed Nothing = Nothing reversed (Just a) = Just ((length str) - a - 1) _findSlash (x:xs) i n | x == '/' || x == '\\' = if i==0 then Just n else _findSlash xs (i-1) (n+1) | True = _findSlash xs i (n+1) _findSlash [] _ _ = Nothing </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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