Replace all spaces in string with ' ' (Cracking the Code Interview)

Write a method to replace all spaces in string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place).

Solustion:

Edit the string from backward.

(1) 1st scan: count how many spaces. Then we know how long the final string.

(2) 2st scan: edit string from end. When we see a space, copy "%20" into the next spots. If it's not space, we copy the original character.


public class Unique {
	public static void main(String arg[])
	{
		char[] ch=new char[30];
		ch[0]='a';
		ch[1]='b';
		ch[2]=' ';
		ch[3]=' ';
		ch[4]='c';
		trans(ch, 5);
	}
	public static void trans(char[] ch, int length){
		int spaceCount=0,newLength=0;
		for(int i=0;i<length;i++){
			if(ch[i]==' ') spaceCount++;
		}
		newLength=length+2*spaceCount;
		int outputLength=newLength;
		ch[newLength]='\0';
		for(int i=length-1;i>0;i--){
			if(ch[i]==' '){
				ch[newLength-1]='0';
				ch[newLength-2]='2';
				ch[newLength-3]='%';
				newLength=newLength-3;
			}else{
				ch[newLength-1]=ch[i];
				newLength--;
			}
		} 
		for(int i=0;i<outputLength;i++){
			System.out.println(ch[i]);
		}
	}
}

The result:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值