面试题4

用 %20 替换字符串中的空格

按照书中的算法,首先找到字符串中空格的数量,扩展字符串空间,然后在源字符串尾部设置一个标识head,在扩展后的字符床尾部设置一个标识last。若head处字符不等于空格,那么直接把该字符赋值给last,head、last同时向前移动一个位置;若head处字符等于空格,那么last处赋值为‘0’,last-1处赋值为‘2’,last-2处赋值为‘%’,head向前移动一个位置,last向前移动三个位置。直到head和last标示(指向)同一个位置为止。

public String replaceSpace(StringBuffer str) {
        int spaceNumber = 0;
        int head = str.length() - 1;
        int last = 0;
        if (str != null) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == ' ') {
                    spaceNumber++;
                    str.append(new char[2]);
                }
            }
            last = head + (2 * spaceNumber);
        }
        while (head < last) {
            char temp = str.charAt(head);
            if (temp != ' ') {
                str.setCharAt(last, temp);
                head--;
                last--;
            } else {
                str.setCharAt(last, '0');
                str.setCharAt(last - 1, '2');
                str.setCharAt(last - 2, '%');
                head--;
                last -= 3;
            }
        }
        return str.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值