如何从字符串中找到第一个非重复字符?

mas*_*san 5 php string

我花了半天的时间试图找出这个,最后我得到了解决方案.但是,我觉得这可以用更简单的方式完成.我认为这段代码不是真的可读.

问题:从字符串中查找第一个非重复字符.

$ string ="abbcabz"

在这种情况下,函数应输出"c".

我使用连接而不是$input[index_to_remove] = '' 从给定字符串中删除字符的原因是因为如果我这样做,它实际上只留下空单元格,以便我的返回值$ input [0]不会返回我想要返回的字符.

例如,

$str = "abc";
$str[0] = '';
echo $str;
Run Code Online (Sandbox Code Playgroud)

这将输出"bc"

但实际上,如果我测试,

var_dump($str);
Run Code Online (Sandbox Code Playgroud)

它会给我:

string(3) "bc"
Run Code Online (Sandbox Code Playgroud)

这是我的意图:

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
Run Code Online (Sandbox Code Playgroud)

码:

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];
}
Run Code Online (Sandbox Code Playgroud)

Cas*_*Chu 10

<?php
    // In an array mapped character to frequency, 
    // find the first character with frequency 1.
    echo array_search(1, array_count_values(str_split('abbcabz')));
Run Code Online (Sandbox Code Playgroud)