如何迭代創建在每個字母后面有撇號的「Murrays」變體?最終結果應該是:在原始字符串的每個字母之後依次生成帶撇號的字符串
"m'rrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's"
如何迭代創建在每個字母后面有撇號的「Murrays」變體?最終結果應該是:在原始字符串的每個字母之後依次生成帶撇號的字符串
"m'rrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's"
您想遍歷名稱,並用撇號重新打印嗎?請嘗試以下操作:
<?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;
?>
我的建議:
<?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', "'");
?>
這裏的另一種解決方案:
$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));
好,這就是爲什麼functionnal編程是這裏
此代碼的工作就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";;
此代碼返回原詞爲列表的末尾,你可以變通方法:)
在這裏你去:
$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)));
我想這是你的功課? – UpTheCreek 2009-07-30 11:34:59
這是用戶暱稱,但似乎不是相同的帳戶。 仍;請參閱http://stackoverflow.com/questions/1198493/mysql-how-to-search-for-spelling-variants-murrays-murrays-etc作爲確切的重複 – 2009-07-30 11:35:38
此問題的用戶是http://stackoverflow.com/users/146970/mehul 昨天的問題的用戶是http://stackoverflow.com/users/146881/mehul – 2009-07-30 11:36:15