Skip to content

Latest commit

 

History

History
36 lines (27 loc) · 699 Bytes

5.md

File metadata and controls

36 lines (27 loc) · 699 Bytes

替换空格

题目

请实现一个函数,将一个字符串中的每个空格替换成 “%20” 。例如,当字符串为 We Are Happy 则经过替换之后的字符串为 We%20Are%20Happy 。

思路

准备临时切片,按字符遍历目标,是空格压入 "%20" ,否则原样压入,然后用空字符串拼接

实现

package main

import (
	"strings"
)

func main() {
	var s = "We Are Happy"
	replaceSpace(s)
}

func replaceSpace(s string) string {
	var tmp = make([]string, 0, len(s))
	for index := range s {
		if string(s[index]) == " " {
			tmp = append(tmp, "%20")
		} else {
			tmp = append(tmp, string(s[index]))
		}
	}
	return strings.Join(tmp, "")
}