如何迭代地创建一个“Murrays”变体,每个字母后面都有一个撇号?最终结果应该是:
"m'rrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's"
答案 0 :(得分:1)
你想要遍历这个名字,并用撇号重新打印它?请尝试以下方法:
<?php
$string = "murrays";
$array = str_split($string);
$length = count($array);
$output = "";
for ($i = 0; $i < $length; $i++) {
for($j = 0; $j < $length; $j++) {
$output .= $array[$j];
if ($j == $i)
$output.= "'";
}
if ($i < ($length - 1))
$output .= ",";
}
print $output;
?>
答案 1 :(得分:1)
我的建议:
<?php
function generate($str, $add, $separator = ',')
{
$split = str_split($str);
$total = count($split) - 1;
$new = '';
for ($i = 0; $i < $total; $i++)
{
$aux = $split;
$aux[$i+1] = "'" . $aux[$i+1];
$new .= implode('', $aux).$separator;
}
return $new;
}
echo generate('murrays', "'");
?>
答案 2 :(得分:0)
这是另一种解决方案:
$str = 'murrays';
$variants = array();
$head = '';
$tail = $str;
for ($i=1, $n=strlen($str); $i<$n; $i++) {
$head .= $tail[0];
$tail = substr($tail, 1);
$variants[] = $head . "'" . $tail;
}
var_dump(implode(',', $variants));
答案 3 :(得分:0)
这就是函数编程在这里的原因
此代码适用于OCAML和F#,您可以轻松地在C#上运行
let generate str =
let rec gen_aux s index =
match index with
| String.length s -> [s]
| _ -> let part1 = String.substr s 0 index in
let part2 = String.substr s index (String.length s) in
(part1 ^ "'" ^ part2)::gen_aux s (index + 1)
in gen_aux str 1;;
generate "murrays";;
此代码返回原始单词作为列表的结尾,您可以解决该问题:)
答案 4 :(得分:0)
你走了:
$array = array_fill(0, strlen($string) - 1, $string);
implode(',', array_map(create_function('$string, $pos', 'return substr_replace($string, "\'", $pos + 1, 0);'), $array, array_keys($array)));