问题描述
编写camel_case
方法,实现将字符串去掉空格,并将每个单词的第一个字母转换成大写。
例如:
camel_case("hello case"); // => "HelloCase"camel_case("camel case word"); // => "CamelCaseWord"
分析
ucfirst数组解决方案
数组元素转换大写
function camel_case(string $s): string {//字符串去空格后判断长度,如果去掉空格后长度为0,就返回空字符串$s = trim($s);if(strlen($s) == 0){return $s;}//转换数组$arr = explode(" ",$s);//遍历,转换大小写,进行字符串拼接$end_s = "";foreach ($arr as $v){$end_s.=ucfirst($v);}return $end_s;}
使用array_map
对数组元素转换后转字符串
function camel_case(string $s): string {return empty($s) ? "" : implode(array_map('ucfirst', explode(" ", trim($s))));}
ucwords
直接转换每个字母后去空格
function camel_case(string $s): string {$upper_case = ucwords($s);return str_replace(' ', '', $upper_case);}
用正则表达式去空格
function camel_case(string $s): string {$s = ucwords($s);$s = preg_replace('/\s(?=)/', '', $s);return $s ;}