• [PHP]算法-替换空格的PHP实现


    替换空格:
    请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
    
    思路:
    1.先循环一遍,找出该字符串中" "空格的个数count
    2.因为要把" "空格替换成 "%20",所以,要倒着数,最后一个空格后面的元素要移动到2*count位置
    3.继续往前遍历,倒数第二个空格后面直到最后空格之间的元素,往后移动(count-1)*2位置
    
    replaceSpace(str)
        count=0
        for i=0;i<count(str);i++
            if str[i]==' ' count++
        for i=count(str)-1;i>=0;i--
            if str[i]!=' '
                str[i+2*count]=str[i]
            else
                count--
                str[i+2*count+1]='%'
                str[i+2*count+2]='2'
                str[i+2*count+3]='0'
    <?php
    function replaceSpace($str)
    {
            $length=strlen($str);//注意字符串长度的函数
            $count=0;
            for($i=0;$i<$length;$i++){
                    if($str[$i]==' '){
                            $count++;
                    }   
            }   
            //倒叙遍历,字符先复制到后面,空格所在位置替换成目标
            for($i=$length-1;$i>=0;$i--){
                    if($str[$i]!=' '){
                            $str[$i+$count*2]=$str[$i];
                    }else{
                            $count--;
                            $str[$i+$count*2]='%';
                            $str[$i+$count*2+1]='2';
                            $str[$i+$count*2+2]='0';
                    }   
            }   
            return $str;
    }
    $str="We Are Happy";
    $str1=replaceSpace($str);
    var_dump($str1);
  • 相关阅读:
    Node.js:事件循环
    Node.js:回调函数
    Node.js:REPL(交互式解释器)
    Node.js:NPM 使用介绍
    Node.js:创建第一个应用
    Node.js:安装配置
    Node.js:教程
    Node.js:目录
    Node.js:template
    虚拟化之xenserver
  • 原文地址:https://www.cnblogs.com/taoshihan/p/9775702.html
Copyright © 2020-2023  润新知