笔记 替换字符串中的空格

总结

首先遍历字符串,得到字符串中的空格数,用到String的charAt方法

然后计算得到新字符char数组的长度,等于原字符长度加上两倍的空格数

再将字符串转换为字符数组移到result字符数组中,用到System.arraycopy函数

然后定义两个index,分别指向原字符长度的尾巴,以及新字符长度的尾巴
    int indexOfOrgChars=orgLength-1;
    int indexOfNewChars=newLength-1;
从后往前移动,这样可以保证移动字符的数目最少,遇到空格字符,把%20插入,这时候只有indexOfNewChars动,而indexOfOriChars不动

非空格字符,两个index都动
package replaceBlank;

public class ReplaceBlank {
    public static int getBlankNum(String testString) {
        int count = 0;
        for (int i = 0; i < testString.length(); i++) {
            String tempString = String.valueOf(testString.charAt(i));
            if (tempString.equals(" ")) {
                count++;
            }
        }

        return count;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String string = "we are here";
        replaceBlank(string);
    }

    static void replaceBlank(String string){
        if (string==null) {
            return;
        }
        int orgLength=string.length();
        int numOfBlank=0;
        for (int i = 0; i < string.length(); i++) {
            String tempString = String.valueOf(string.charAt(i));
            if (tempString.equals(" ")) {
                numOfBlank++;
            }
        }
        int newLength=orgLength+2*numOfBlank;
        char[] tempChars=new char[newLength];
        System.arraycopy(string.toCharArray(), 0, tempChars, 0, string.length());
        System.out.println("orgLength:"+orgLength+"\n"+"numOfBlank:"+numOfBlank);
        int indexOfOrgChars=orgLength-1;
        int indexOfNewChars=newLength-1;
        while (indexOfOrgChars>=0&&indexOfNewChars!=indexOfOrgChars) {
            if (tempChars[indexOfOrgChars]==' ') {
                tempChars[indexOfNewChars--]='%';
                tempChars[indexOfNewChars--]='2';
                tempChars[indexOfNewChars--]='0';
            }else {
                tempChars[indexOfNewChars--]=tempChars[indexOfOrgChars];
            }
            indexOfOrgChars--;
        }
        System.out.println(tempChars);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值