【字符串1】-替换空格

【题目】实现一个函数 将语句中的空格转换成字符“%20”

package com.exe1.offer;
//2 实现一个函数 将语句中的空格转换成字符“%20”
/**
 * 思路: 1 得到原字符串长度和加入空格后的长度;
 *          2 定义两个指针,分别指向原字符串和加入空格后字符串的最后一格;
 *       3 将原字符串复制到新的数组当中;
 *       4 只要旧指针和指针没相遇,就逐步操作,具体步骤如下。
 * @author WGS
 *
 */
       
public class ReplaceSpace {
    //得到字符串中空格数
    public int getBlankNum(String str){
        int count=0;
        for(int i=0;i<str.length();i++){
            if(str.charAt(i)==' '){
                count++;
            }
        }
        return count;
    }
    //替换
    public String replaceBlank(String string){
        String str=string.toString();
        //统计空格数
        int count=getBlankNum(str);
        //获取原来字符串的长度
        int originalStrLength=str.toCharArray().length;
        //计算替换空格之后需要的长度
        int newStrLength=originalStrLength+count*2;
         //把原字符串复制到tempArray数组中
        char[] tempArray=new char[newStrLength];
        System.arraycopy(str.toCharArray(), 0, tempArray, 0, originalStrLength);
        //定义两个指针
        int originalIndex=originalStrLength-1;
        int newIndex=newStrLength-1;
        
        //当originalStrIndex == newStrIndex的时候替换完毕
        while(originalIndex>=0 && originalIndex!= newIndex) {
            if(tempArray[originalIndex]==' '){//当 旧指针指向的值为空格时(此时新指针指向最开始),将空格的地方改为字符串%20
                tempArray[newIndex--]='%';
                tempArray[newIndex--]='2';
                tempArray[newIndex--]='0';
            }else{
                tempArray[newIndex--]=tempArray[originalIndex];//当旧指针指向的值不是空格时,就将其值复制到新指针指向的空格,一点一点往前复制,直至遇到空格。
            }
            originalIndex--;
        }
        
        return new String(tempArray);
        
        
    }
    public static void main(String[]  args){
        String s=new ReplaceSpace().replaceBlank("We are happy");
        System.out.println(s);
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值