3 回答
TA贡献1831条经验 获得超4个赞
请尝试以下方法:
function getNonRepeatingCharacters($str) {
$counter = [];
$spllitted = str_split($str);
foreach($spllitted as $s) {
if(!isset($counter[$s])) $counter[$s] = 0;
$counter[$s]++;
}
$non_repeating = array_keys(array_filter($counter, function($c) {
return $c == 1;
}));
return $non_repeating;
}
$string = "abclkjabc";
$handle = getNonRepeatingCharacters($string);
TA贡献1878条经验 获得超4个赞
函数式编程并且没有临时变量声明:
创建字符数组
统计每个字符出现的次数
仅保留出现过一次的字符(
array_filter()
也可以,但更冗长)重新加入符合条件的角色
echo implode(
array_keys(
array_intersect(
array_count_values(
str_split('abclkjabc'),
),
[1]
)
)
);
$unique = '';
foreach (array_count_values(str_split('abclkjabc')) as $char => $count) {
if ($count === 1) {
$unique .= $char;
}
}
echo $unique;
输出:
lkj
可以使用 获取输出字符串的长度strlen()
。
您可以使用 来计算字符值,而不是拆分字符串和计数数组值count_chars()
。(演示)
$string = 'abclkjabc';
$notRepeated = [];
foreach (count_chars($string, 1) as $char => $count) {
if ($count === 1) {
$notRepeated[] = chr($char);
}
}
var_export($notRepeated);
echo "\nCount = " . count($notRepeated);
最终,如果您只需要计算非重复字符的数量,这一行就可以满足您的要求。(演示)
echo count(array_filter(count_chars($string, 1), fn($count) => $count === 1));
TA贡献1852条经验 获得超7个赞
尝试这个:
function getNonRepeatingChars($str) {
$uniqueLetters = '';
$multipleLetters = '';
$arrayStr = str_split($str);
foreach ($arrayStr as $index => $letter) {
if (strpos($multipleLetters, $value) !== false || strpos($str, $value, $index + 1) !== false) {
$multipleLetters .= $value;
continue;
}
$uniqueLetters .= $value;
}
return $uniqueLetters;
}
echo getNonRepeatingChars('abclkjabc'); // lkj
- 3 回答
- 0 关注
- 113 浏览
添加回答
举报