今回挑戦するプログラミング問題
codewars 6級
「Mexican Wave」
実現したいこと
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
受け取った文字列を左から順に大文字へ変換していきたい。
コーディング
function wave($hello){
for($i = 0, $res = []; $i < strlen($hello); $i++) {
if($hello[$i] !== " ") {
$res[] = substr_replace($hello, strtoupper($hello[$i]), $i, 1);
}
}return $res;
}
- 文字の数だけfor文で回す
- 新しい配列を用意して値を入れていく
- substr_replace(置換したい文字列, 置換後の文字列, 開始位置, 置換する長さ)
- 置換する長さは1つで固定しつつ、開始位置をfor文でズラして取得