/**
*
*/
package Chapter_8;
import java.util.Scanner;
/**
* @author MohnSnow
* @time 2015年5月22日 上午9:57:30
*
*/
public class chapter8_1_4 {
/**
* @param argsmengdx
* -fnst
* @title 空格全部替换为%20,不建议使用字符串处理,使用字符数组去处理
*/
private static void spaceReplace(String str_a) {
char[] temp = str_a.toCharArray();
int space_count = 0;
int new_count = temp.length;
// System.out.println(temp[4]);一个字符占一个位置
for (int i = 0; i < temp.length; i++) {
if (temp[i] == ' ') {// 此处应该注意形式:if (temp[i] ==
// " "),区分字符串和字符的空格的表现形式否则会提示Incompatible
// operand types char and String
space_count++;
}
}
new_count += 2 * space_count;// 空格转换为%,另外还有两个字符0和2
char[] result = new char[new_count];
for (int i = 0, j = 0; i < temp.length && j < new_count; i++) {
if (temp[i] == ' ') {
result[j++] = '%';
result[j++] = '2';
result[j++] = '0';
} else {
result[j++] = temp[i];
}
}
System.out.println(result);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.nextLine();
spaceReplace(a);
}
}
CTCI---8.1.4
最新推荐文章于 2024-05-10 10:01:05 发布