前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指offer--替换空格

剑指offer--替换空格

作者头像
AI那点小事
发布2020-04-18 20:22:13
3190
发布2020-04-18 20:22:13
举报

请实现一个函数,将一个字符串中的空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。


思路: 遍历字符串,遇见“ 后替换成“%20”并把控制下标的变量加3,如果不是则继续,即控制下标的变量加1。


Java代码如下:

public class Solution {
    public int Find(int start , char c,StringBuffer str){
        int index = -1;
        char[] ch = str.toString().toCharArray();
        for ( int i = start ; i < str.length() ; i++){
            if ( ch[i] == c){
                index = i;
                break;
            }
        }
        return index;
    }

    public String replaceSpace(StringBuffer str) {
        String s = "%20";
        for ( int i = 0 ; i < str.length() ; ){
            int index = Find(i, ' ', str);
            if ( index != -1){
                str.replace(index, index+1,s);
                i = i + 3;
                continue;
            }else{
                i++;
                continue;
            }
        }
        return str.toString();
    }
}

C++代码如下:

class Solution {
public:
    void replaceSpace(char *str,int length) {
        int oldlength = 0;
        int newlength = 0;
        int i = 0;
        //首先遍历数组计算新数组长度 
        while(str[i] != '\0'){
            oldlength++; 
            if(str[i] == ' '){
                newlength += 3;
            }else{
                newlength++;
            }
            i++;
        }
        //开始替换
        while(oldlength >= 0){
            if(str[oldlength] == ' '){
                str[newlength--] = '0';
                str[newlength--] = '2';
                str[newlength--] = '%';
            }else{
                str[newlength--] = str[oldlength];
            }
            oldlength--;
        } 
    } 
};

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档