How to find first non-repetitive character from a string?

Posted by masato-san on Stack Overflow See other posts from Stack Overflow or by masato-san
Published on 2010-06-02T06:58:36Z Indexed on 2010/06/02 7:03 UTC
Read the original article Hit count: 613

Filed under:
|
|

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.

Problem: Find first non-repetitive character from a string.

$string = "abbcabz"

In this case, the function should output "c".

The reason I use concatenation instead of $input[index_to_remove] = '' 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.

For instance,

$str = "abc";
$str[0] = '';
echo $str;

This will output "bc"

But actually if I test,

var_dump($str);

it will give me:

string(3) "bc"

Here is my intention:

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:

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];
}

© Stack Overflow or respective owner

Related posts about php

Related posts about string