如何替換 func 函數(shù) (s, old, new [] bytes, n int) [] bytes which,給定三個字節(jié)切片,s、old、new 和一個整數(shù) n,返回一個對應(yīng)于 s 的切片,其中第 n 次出現(xiàn)的 old 被 new 替換。如果這種情況不存在,函數(shù)返回 s 而不改變它?謝謝import ( "fmt" "os" "strconv")func main() { s := os.Args[1] old := os.Args[2] new := os.Args[3] n, _ := strconv.Atoi(os.Args[4]) fmt.Println(s) replaced := replace([]byte(s), []byte(old), []byte(new), n) fmt.Println(string(replaced))}func replace(s, old, new []byte, i int) (replaced []byte) {}```
1 回答

陪伴而非守候
TA貢獻1757條經(jīng)驗 獲得超8個贊
您可以嘗試使用 的組合bytes.SplitAfter,它將在分隔符(對您來說是舊的)之后拆分您的原始字符串,bytes.Replace()在切片的 N 元素上,然后bytes.Join重新組合您的原始字符串。
您應(yīng)該檢查非常清楚的文檔:)
package main
import (
"bytes"
"fmt"
)
func main() {
str := []byte("oink oink oink oink")
old := []byte("k")
new := []byte("X")
splitedStr := bytes.SplitAfter(str, old)
splitedStr[2] = bytes.Replace(splitedStr[2], old, new, -1)
fmt.Printf("%s", bytes.Join(splitedStr, []byte("")))
}
- 1 回答
- 0 關(guān)注
- 143 瀏覽
添加回答
舉報
0/150
提交
取消