strings.builder 介紹

範例

package main

import (
    "fmt"
    "strings"
)

func main() {
    // Reset()
    // Len()
    // String()
    var b1 strings.Builder
    b1.WriteString("ABC")
    b2 := b1
    fmt.Println(b2.Len())    // 3
    fmt.Println(b2.String()) // ABC
    b2.Reset()
    b2.WriteString("DEF")
    fmt.Println(b2.String()) // DEF
    fmt.Println(b1.String())  // ABC
}

// 範例二
var b strings.Builder
b.Grow(32)   // 可事先alloc memory
for i, p := range []int{2, 3, 5, 7, 11, 13} {
    fmt.Fprintf(&b, "%d:%d, ", i+1, p)
}
s := b.String()   // no copying
s = s[:b.Len()-2] // no copying (removes trailing ", ")
fmt.Println(s)

大小寫轉換

package main

import(
   "fmt"
   "strings"
)

func main() {
    var str strings.Builder
    s := "a123abcde"
    str.WriteString(strings.ToUpper(s[0:1]))   // 把字首轉為大寫
    str.WriteString(s[1:])                     // 取得a之後字串
    fmt.Println(str.String())
}