您的位置:首页 > 其它

Cracking the coding interview--Q1.5

2014-10-20 16:09 351 查看
原文:

Write a method to replace all spaces in a string with ‘%20’.

译文:

写一个函数,把字符串中所有的空格替换为%20 。

package chapter_1_arraysandstring;

import java.util.Scanner;

/**
* 写一个函数,把字符串中所有的空格替换为%20
*
* @author LiangGe
*
*/
public class Question_1_5 {

/**
* 通过StringBuffer拼接结果,遍历替换
*/
public static String spaceReplace(String str) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
result.append("%20");
} else {
result.append(str.charAt(i));
}
}
return result.toString();
}

public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String str = scanner.nextLine();
str = spaceReplace(str);
System.out.println(str);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法