Skip to content

Latest commit

 

History

History
48 lines (39 loc) · 763 Bytes

05. 替换空格.md

File metadata and controls

48 lines (39 loc) · 763 Bytes

解题思路

用库函数或者遍历替换都很方便

1. 遍历替换

func replaceSpace(s string) string {
    str := ""
    for _, r := range s {
        if r == ' ' {
            str += "%20"
            continue
        }
        str += string(r)
    }
    return str
}

2. 使用 string.Builder

func replaceSpace(s string) string {
    str := strings.Builder{}
    for i := range s {
        if s[i] == ' ' {
            str.WriteString("%20")
        } else {
            str.WriteByte(s[i])
        }
    }
    return str.String()
}

3. 库函数

实际也是使用的 Builder

func replaceSpace(s string) string {
    return strings.ReplaceAll(s, " ", "%20")
}