http://ac.jobdu.com/problem.php?pid=1510
题目1510:替换空格
从后向前替换,另外注意在读写时要用Scanner的hasNextLine 才能读入white space
题目1510:替换空格
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class S4 {
public static void main(String[] args) throws FileNotFoundException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("S4.in"));
System.setIn(in);
Scanner cin = new Scanner(System.in);
while (cin.hasNextLine()) {
String s = cin.nextLine();
System.out.println(replace(s));
}
}
public static String replace(String s){
int len = s.length();
char[] olds = s.toCharArray();
int space = 0;
for(int i=0; i<olds.length; i++){
if(olds[i] == ' '){
space++;
}
}
int newLen = len + 2*space;
char[] news = new char[newLen];
int i = len-1;
int j = newLen-1;
while(i >= 0){
if(olds[i] != ' '){
news[j] = olds[i];
j--;
}else{
news[j--] = '0';
news[j--] = '2';
news[j--] = '%';
}
i--;
}
return new String(news);
}
}