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:

本文介绍了一种将字符串中的所有空格替换为'%20'的方法。通过两次扫描实现:第一次扫描计算空格数量并确定最终字符串长度;第二次从字符串末尾开始替换,遇到空格则替换成'%20',非空格字符直接复制。
3439

被折叠的 条评论
为什么被折叠?



