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);
}
}
本文详细解析了一个关于字符串处理的编程任务,即在给定的字符串中将空格替换为%20。通过逐步解释代码逻辑,展示了如何实现从后向前替换字符串中的空格,并在读写操作中正确处理空白字符。

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



