算法--空格替换

转载请标明出处http://www.cnblogs.com/haozhengfei/p/bca26fda99153a1e4b0f8fedfe91bc95.html 


空格替换

 
空格替换练习
 

第10节 空格替换练习题

 

请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。

给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。

测试样例:
"Mr John Smith”,13
返回:"Mr%20John%20Smith"
 
”Hello  World”,12
返回:”Hello%20%20World”
 
 
 
1
import java.util.*;
2

3
public class Replacement {
4
    public String replaceSpace(String iniString, int length) {
5
        // "  ab cd dd dnf" or "abc dd   smq"
6
        char[] charAll = iniString.toCharArray();
7
        // 遍历
8
        StringBuilder sb = new StringBuilder();
9
        for (int i = 0; i < charAll.length; i++) {
10
            if(charAll[i] == " ".charAt(0)){
11
                sb.append("%20");
12
            }
13
            else{
14
                sb.append(charAll[i]);
15
            }
16
        }
17
        return sb.toString();
18
    }
19
}
 
 
您的代码已保存
答案正确:恭喜!您提交的程序通过了所有的测试用例
 
原文地址:https://www.cnblogs.com/haozhengfei/p/bca26fda99153a1e4b0f8fedfe91bc95.html