我想在PHP中反转字符串的元音。我已经在下面的代码中编写了此代码,但是结果集为空。
范例-
“ hello”,返回“ holle”
“ leetcode”,返回“ leotcede”
提前谢谢我帮助我实现这一目标。
<?php
function reverseVowels($string) {
$result = '';
$string = array();
$vowels = array();
$strlength = count($string);
for ($i=0; $i < $strlength; $i++) {
$orig = $strlength[$i];
$char = strtolower($strlength[$i]);
if ($char === 'a' || $char === 'e' || $char === 'i' || $char === 'o' || $char === 'u') {
array_push($vowels, $orig);
$orig = null;
}
array_push($string, $orig);
}
$new_strlength = count($string);
for ($i=0; $i < $new_strlength; $i++) {
if (!$string[$i]) {
$string[$i] = array_splice($vowels, count($vowels) - 1, 1);
}
}
$result = $string;
return $result;
}
$res = reverseVowels("hello hello");
print_r($res);
//"hello", return "holle"
//"leetcode", return "leotcede"
?>
这是更改后的工作代码:
function reverseVowels($str) {
$result = '';
$string = array();
$vowels = array();
$strlength = count($str);
for ($i=0; $i < strlen($str); $i++) {
$orig = $str[$i];
$char = strtolower($str[$i]);
if ($char === 'a' || $char === 'e' || $char === 'i' || $char === 'o' || $char === 'u') {
array_push($vowels, $orig);
$orig = null;
}
array_push($string, $orig);
}
$new_strlength = count($string);
for ($i=0; $i < count($string); $i++) {
if (!$string[$i]) {
$string[$i] = array_splice($vowels, count($vowels) - 1, 1)[0];
}
}
$result = $string;
return $result;
}
$res = reverseVowels("leetcode");
echo "<pre>";
print_r($res);
echo "</pre>";
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句