-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathQ5_ReplaceBlankInString.java
54 lines (44 loc) · 1.49 KB
/
Q5_ReplaceBlankInString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package chapter2;
import org.junit.Assert;
import org.junit.Test;
import java.util.Objects;
/**
* 题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如,
* 输入"Wearehappy.”,则输出"We%20are%20happy.
*
* @author flying
*/
public class Q5_ReplaceBlankInString {
private String replaceBlank(String str) {
if (str == null || str.length() == 0) {
return str;
}
int blankCount = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
blankCount ++;
}
}
char[] newStr = new char[str.length() + blankCount * 2];
int j = newStr.length - 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) == ' ') {
newStr[j--] = '0';
newStr[j--] = '2';
newStr[j--] = '%';
} else {
newStr[j--] = str.charAt(i);
}
}
return new String(newStr);
}
@Test
public void test() {
Assert.assertTrue(Objects.equals(replaceBlank(""), ""));
Assert.assertTrue(Objects.equals(replaceBlank(null), null));
Assert.assertTrue(Objects.equals(replaceBlank("Hello world"), "Hello%20world"));
Assert.assertTrue(Objects.equals(replaceBlank(" Hello world "), "%20Hello%20world%20"));
Assert.assertTrue(Objects.equals(replaceBlank("Helloworld"), "Helloworld"));
}
}