1、replaceSpace

题目

请实现一个函数,把字符串中的每个空格替换为”%20”。

输入

“We are happy”

输出

“We%20are%20happy”

实现

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
 public static String replaceSpace(String input) {
if (input == null) {
return null;
}
if ("".equals(input)) {
return null;
}
//计算空格的个数
char[] chars = input.toCharArray();
int numOfSpace = 0;
for (char curChar : chars) {
if (curChar == ' ') {
numOfSpace++;
}
}
//创建一个新的字符数组
char[] newChars = new char[chars.length + numOfSpace * 2];
int indexOfNewChar = -1;
for (char curChar : chars) {
if (curChar != ' ') {
newChars[++indexOfNewChar] = curChar;
} else {
newChars[++indexOfNewChar] = '%';
newChars[++indexOfNewChar] = '2';
newChars[++indexOfNewChar] = '0';
}
}
return String.valueOf(newChars);
}

单元测试

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
package com.easyliu.test.replace_space;

import org.junit.Assert;
import org.junit.Test;

public class ReplaceSpaceTest {

@Test
public void testNullInput() {
Assert.assertNull(ReplaceSpace.replaceSpace(null));
}

@Test
public void testEmptyInput() {
Assert.assertNull(ReplaceSpace.replaceSpace(""));
}

@Test
public void testNormalSpace() {
String expect = "we%20are%20happy";
String result = ReplaceSpace.replaceSpace("we are happy");
Assert.assertEquals(expect, result);
}

@Test
public void testMultiSpace() {
String expect = "we%20%20are%20%20happy";
String result = ReplaceSpace.replaceSpace("we are happy");
Assert.assertEquals(expect, result);
}

@Test
public void testSingleSpace() {
String expect = "%20";
String result = ReplaceSpace.replaceSpace(" ");
Assert.assertEquals(expect, result);
}

@Test
public void testNoSpace() {
String expect = "we";
String result = ReplaceSpace.replaceSpace("we");
Assert.assertEquals(expect, result);
}
}