题目:请事先一个函数,把字符串中的每个空格替换成“%20”。
import java.io.*;
import java.util.*;
public class exercise2 {
public static void main(String[] args) throws IOException {
// Scanner s=new Scanner(System.in);
// String line=s.nextLine();
InputStream in=System.in;
InputStreamReader isr=new InputStreamReader(in);
BufferedReader bufr=new BufferedReader(isr);
String line=null;
while((line=bufr.readLine())!=null){
int num=0;
char[] c=line.toCharArray();
for(int i=0;i<line.length();i++){
if(c[i]==' ') num++;
}
System.out.println(c.toString()+";");
char newc[]=new char[c.length +num*2];
int j=newc.length-1;
int i = c.length-1;
System.out .println(j);
System.out .println(i);
while(j>=0&&i>=0)
{
if(c[i]!=' '){
newc[j--]=c[i--];
}
else{
newc[j--]='0';
newc[j--]='2';
newc[j--]='%';
i--;
}
}
System.out.println(c);
System.out.println(newc);
}
}
//别人的方法,将空格替换为任意的几个字符
public static void repalce(char[] oldchar,char[] replacement){
int sumOfSpace = 0;
for(int i = 0;i < oldchar.length;i++){
if(oldchar[i] == ' ')
sumOfSpace++;
}
if(sumOfSpace == 0){
return ;
}
char [] newchar = new char[oldchar.length + (replacement.length-1) * sumOfSpace];
//指向被替换字符串的最后一个元素
int pOld = oldchar.length - 1;
//指向替换字符串的最后一个元素
int pNew = newchar.length - 1;
while(pNew >= 0){
if(oldchar[pOld] == ' '){
pOld--;
for(int j = replacement.length - 1;j >= 0;j--){
newchar[pNew--] = replacement[j];
}
}else{
newchar[pNew--] = oldchar[pOld--];
}
}
for(char c:newchar){
System.out.print(c);
}
}
}