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

来源:互联网 发布:html5 360全景源码 编辑:程序博客网 时间:2024/06/05 18:04

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:


0 0
原创粉丝点击