方法一:
直接新建数组然后遍历添加。注意转换成byte
func replaceSpace(s string) string {
res := make([]byte, 0)
for _, v := range s {
if v == ' ' {
res = append(res, []byte("%20")...)
} else {
res = append(res, byte(v))
}
}
return string(res)
}
方法二:扩展原数组
func replaceSpace(s string) string {
// 计算空格数量
count := 0
b := []byte(s)
for _, v := range b {
if v == ' ' {
count++
}
}
oldLen := len(b)
newLen := 2 * count
temp := make([]byte, newLen)
b = append(b, temp...)
i := oldLen - 1
j := oldLen + newLen - 1
for i >= 0 {
if b[i] == ' ' {
b[j] = '0'
b[j-1] = '2'
b[j-2] = '%'
j -= 2
} else {
b[j] = b[i]
}
i--
j--
}
return string(b)
}