替换空格-leetcode

1. 地址

https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

2. 思路

临时变量 $ret
将字符串转成数组,遍历数组,拼接字符串,此过程中将空格转成 %20

3. 代码

class Solution {

    /**
     * @param String $s
     * @return String
     */
    function replaceSpace($s) {
        $ret = [];
        $strArr = str_split($s);

        foreach ($strArr as $item) {
            if ($item == ' ') {
                $ret[] = '%20';
            } else {
                $ret[] = $item;
            }
        }
        return implode('', $ret);
    }
}
posted @ 2020-05-31 15:06  吴丹阳-V  阅读(152)  评论(0编辑  收藏  举报