Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to find first non-repetitive character from a string?
    text
    copied!<p>I've spent half day trying to figure out this and finally I got working solution. However, I feel like this can be done in simpler way. I think this code is not really readable.</p> <p>Problem: Find first non-repetitive character from a string.</p> <p>$string = "abbcabz"</p> <p>In this case, the function should output "c".</p> <p>The reason I use concatenation instead of <code>$input[index_to_remove] = ''</code> in order to remove character from a given string is because if I do that, it actually just leave empty cell so that my return value $input[0] does not not return the character I want to return.</p> <p>For instance, </p> <pre><code>$str = "abc"; $str[0] = ''; echo $str; </code></pre> <p>This will output "bc"</p> <p>But actually if I test,</p> <pre><code>var_dump($str); </code></pre> <p>it will give me:</p> <pre><code>string(3) "bc" </code></pre> <p>Here is my intention:</p> <pre><code>Given: input while first char exists in substring of input { get index_to_remove input = chars left of index_to_remove . chars right of index_to_remove if dupe of first char is not found from substring remove first char from input } return first char of input </code></pre> <p>Code:</p> <pre><code>function find_first_non_repetitive2($input) { while(strpos(substr($input, 1), $input[0]) !== false) { $index_to_remove = strpos(substr($input,1), $input[0]) + 1; $input = substr($input, 0, $index_to_remove) . substr($input, $index_to_remove + 1); if(strpos(substr($input, 1), $input[0]) == false) { $input = substr($input, 1); } } return $input[0]; } </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