Generate a string with an apostrophe after each letter of the original string in turn

How can I iteratively create a version of "Murray" that has an apostrophe after each letter? The end result should be:

"m'rrays,mu'rrays,mur'rays,murr'ays,murra'ys,murray's" 
+4
source share
5 answers

Do you want to iterate over a name and retype it with an apostrophe? Try the following:

 <?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
source

My suggestion:

 <?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', "'"); ?> 
+1
source

Here is another solution:

 $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)); 
0
source

well that's why functional programming is here

this code works on OCAML and F #, you can easily run it in 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";; 

this code returns the original word as the end of the list, you can workaround :)

0
source

Here you go:

 $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))); 
0
source

All Articles