字符串替换空格

字符串替换空格

在一个字符串中用”%20“替换所有空格
思路:
在原有字符串长度上开辟新的空间,该空间就是把所有空格换成三个字符的长度也就是(3-1)* 空格的个数,
然后有两个指针一个指在原来的字符串尾一个指在最新的尾,newindex跟着oldindex走,碰到空格就把newindex前三个都变成%20,碰到不是空格就把oldindex的东西给newindex的位置,一直下去,就能完成字符串的更新。

  public static void replace(StringBuffer string){
        int oldindex=string.length()-1;
        int spacount=0;
        for(int i=0;i<string.length();i++){
            if(string.charAt(i)==' '){
                spacount++;
            }
        }
        int newlength=string.length()+2*spacount;
        string.setLength(newlength);//开辟新的空间
        int newindex = string.length()-1;
        while(oldindex>=0 && oldindex<newindex){
            if(string.charAt(oldindex)==' '){
                string.setCharAt(newindex--,'0');
                string.setCharAt(newindex--,'2');
                string.setCharAt(newindex--,'%');
            }else{
                string.setCharAt(newindex--,string.charAt(oldindex));
            }
            oldindex--;
        }

    }

测试:

  public static void main(String[] args) {
        StringBuffer stringBuffer = new StringBuffer("We are happy ");
        replace(stringBuffer);
        System.out.println(stringBuffer);



    }
We%20are%20happy%20

Process finished with exit code 0

方法二 c++;

class Solution {
public:
    string replaceSpaces(string &str) {
        string res;
        int sum = 0;
        for(auto x : str){
            if(x == ' ')res+="%20";
            else res+=x;
        }
        return res;
        
       
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值