出鞘之剑指offer-第5题 (替换空格)

题目:

实现一个函数,把字符串中的每个空格替换成“%20”。

例如:输入“We are happy”,则输出“We%20are%20happy”。

分析一: 

使用stringbuilder,遍历原字符串,往stringbuilder对象中追加,碰到空格,追加%20。

代码一: 

package offer.xzs.four;


public class ReplaceSpace02 {
    public static void main(String[] args) {
        String str = " We  are happy ";
        String s = replaceStr(str);
        System.out.println(s);
    }

    public static String replaceStr(String str) {
        if (str == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (String.valueOf(str.charAt(i)).equals(" ")) {
                sb.append("%20");
            } else {
                sb.append(String.valueOf(str.charAt(i)));
            }
        }

        return sb.toString();
    }

}

 分析二:

先遍历一遍,得到空格的数量,每一个空格在字符串后面追加两倍的字符空间,设置两个指针,一个指向原字符串的末尾,一个指向现在字符串的末尾,从后往前遍历。

代码二: 

package offer.xzs.four;


public class ReplaceSpace03 {
    public static void main(String[] args) {
        String str = " We  are happy  ";
        String s = replaceStr(str);
        System.out.println(s);
    }

    public static String replaceStr(String str) {
        if (str == null) {
            return null;
        }
        int index1 = str.length() - 1;
        for (int i = 0; i <= index1; i++) {
            if (String.valueOf(str.charAt(i)).equals(" ")) {
                str += "  ";
            }
        }

        int index2 = str.length() - 1;
        char[] chars = str.toCharArray();

        while (index1 >= 0 && index2 > index1) {
            char c = chars[index1--];
            if (c == ' ') {
                chars[index2--] = '0';
                chars[index2--] = '2';
                chars[index2--] = '%';
            } else {
                chars[index2--] = c;
            }
        }
        String result = new String(chars);
        return result;
    }

    public static String replaceStr1(String str) {
        str.replace(" ", "%20");
        return str;
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值