当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > go语言中strings包的用法汇总

go语言中strings包的用法汇总

2018年11月08日  | 移动技术网IT编程  | 我要评论

strings 包中的函数和方法

// strings.go

------------------------------------------------------------

// count 计算字符串 sep 在 s 中的非重叠个数
// 如果 sep 为空字符串,则返回 s 中的字符(非字节)个数 + 1
// 使用 rabin-karp 算法实现
func count(s, sep string) int

func main() {
s := "hello,世界!!!!!"
n := strings.count(s, "!")
fmt.println(n) // 5
n = strings.count(s, "!!")
fmt.println(n) // 2
}

------------------------------------------------------------

// contains 判断字符串 s 中是否包含子串 substr
// 如果 substr 为空,则返回 true
func contains(s, substr string) bool

func main() {
s := "hello,世界!!!!!"
b := strings.contains(s, "!!")
fmt.println(b) // true
b = strings.contains(s, "!?")
fmt.println(b) // false
b = strings.contains(s, "")
fmt.println(b) // true
}

------------------------------------------------------------

// containsany 判断字符串 s 中是否包含 chars 中的任何一个字符
// 如果 chars 为空,则返回 false
func containsany(s, chars string) bool

func main() {
s := "hello,世界!"
b := strings.containsany(s, "abc")
fmt.println(b) // false
b = strings.containsany(s, "def")
fmt.println(b) // true
b = strings.contains(s, "")
fmt.println(b) // true
}

------------------------------------------------------------

// containsrune 判断字符串 s 中是否包含字符 r
func containsrune(s string, r rune) bool

func main() {
 s := "hello,世界!"
 b := strings.containsrune(s, '\n')
 fmt.println(b) // false
 b = strings.containsrune(s, '界')
 fmt.println(b) // true
 b = strings.containsrune(s, 0)
 fmt.println(b) // false
}

------------------------------------------------------------

// index 返回子串 sep 在字符串 s 中第一次出现的位置
// 如果找不到,则返回 -1,如果 sep 为空,则返回 0。
// 使用 rabin-karp 算法实现
func index(s, sep string) int
func main() {
 s := "hello,世界!"
 i := strings.index(s, "h")
 fmt.println(i) // -1
 i = strings.index(s, "!")
 fmt.println(i) // 12
 i = strings.index(s, "")
 fmt.println(i) // 0
}

------------------------------------------------------------

// lastindex 返回子串 sep 在字符串 s 中最后一次出现的位置
// 如果找不到,则返回 -1,如果 sep 为空,则返回字符串的长度
// 使用朴素字符串比较算法实现
func lastindex(s, sep string) int

func main() {
 s := "hello,世界! hello!"
 i := strings.lastindex(s, "h")
 fmt.println(i) // -1
 i = strings.lastindex(s, "h")
 fmt.println(i) // 14
 i = strings.lastindex(s, "")
 fmt.println(i) // 20
}

------------------------------------------------------------

// indexrune 返回字符 r 在字符串 s 中第一次出现的位置
// 如果找不到,则返回 -1
func indexrune(s string, r rune) int
func main() {
 s := "hello,世界! hello!"
 i := strings.indexrune(s, '\n')
 fmt.println(i) // -1
 i = strings.indexrune(s, '界')
 fmt.println(i) // 9
 i = strings.indexrune(s, 0)
 fmt.println(i) // -1
}

------------------------------------------------------------

// indexany 返回字符串 chars 中的任何一个字符在字符串 s 中第一次出现的位置
// 如果找不到,则返回 -1,如果 chars 为空,则返回 -1
func indexany(s, chars string) int

func main() {
 s := "hello,世界! hello!"
 i := strings.indexany(s, "abc")
 fmt.println(i) // -1
 i = strings.indexany(s, "dof")
 fmt.println(i) // 1
 i = strings.indexany(s, "")
 fmt.println(i) // -1
}

------------------------------------------------------------

// lastindexany 返回字符串 chars 中的任何一个字符在字符串 s 中最后一次出现的位置
// 如果找不到,则返回 -1,如果 chars 为空,也返回 -1
func lastindexany(s, chars string) int

func main() {
 s := "hello,世界! hello!"
 i := strings.lastindexany(s, "abc")
 fmt.println(i) // -1
 i = strings.lastindexany(s, "def")
 fmt.println(i) // 15
 i = strings.lastindexany(s, "")
 fmt.println(i) // -1
}

------------------------------------------------------------

// splitn 以 sep 为分隔符,将 s 切分成多个子串,结果中不包含 sep 本身
// 如果 sep 为空,则将 s 切分成 unicode 字符列表。
// 如果 s 中没有 sep 子串,则将整个 s 作为 []string 的第一个元素返回
// 参数 n 表示最多切分出几个子串,超出的部分将不再切分。
// 如果 n 为 0,则返回 nil,如果 n 小于 0,则不限制切分个数,全部切分
func splitn(s, sep string, n int) []string
func main() {
 s := "hello, 世界! hello!"
 ss := strings.splitn(s, " ", 2)
 fmt.printf("%q\n", ss) // ["hello," "世界! hello!"]
 ss = strings.splitn(s, " ", -1)
 fmt.printf("%q\n", ss) // ["hello," "世界!" "hello!"]
 ss = strings.splitn(s, "", 3)
 fmt.printf("%q\n", ss) // ["h" "e" "llo, 世界! hello!"]
}

------------------------------------------------------------

// splitaftern 以 sep 为分隔符,将 s 切分成多个子串,结果中包含 sep 本身
// 如果 sep 为空,则将 s 切分成 unicode 字符列表。
// 如果 s 中没有 sep 子串,则将整个 s 作为 []string 的第一个元素返回
// 参数 n 表示最多切分出几个子串,超出的部分将不再切分。
// 如果 n 为 0,则返回 nil,如果 n 小于 0,则不限制切分个数,全部切分
func splitaftern(s, sep string, n int) []string

func main() {
 s := "hello, 世界! hello!"
 ss := strings.splitaftern(s, " ", 2)
 fmt.printf("%q\n", ss) // ["hello, " "世界! hello!"]
 ss = strings.splitaftern(s, " ", -1)
 fmt.printf("%q\n", ss) // ["hello, " "世界! " "hello!"]
 ss = strings.splitaftern(s, "", 3)
 fmt.printf("%q\n", ss) // ["h" "e" "llo, 世界! hello!"]
}

------------------------------------------------------------

// split 以 sep 为分隔符,将 s 切分成多个子切片,结果中不包含 sep 本身
// 如果 sep 为空,则将 s 切分成 unicode 字符列表。
// 如果 s 中没有 sep 子串,则将整个 s 作为 []string 的第一个元素返回
func split(s, sep string) []string

func main() {
 s := "hello, 世界! hello!"
 ss := strings.split(s, " ")
 fmt.printf("%q\n", ss) // ["hello," "世界!" "hello!"]
 ss = strings.split(s, ", ")
 fmt.printf("%q\n", ss) // ["hello" "世界! hello!"]
 ss = strings.split(s, "")
 fmt.printf("%q\n", ss) // 单个字符列表
}

------------------------------------------------------------

// splitafter 以 sep 为分隔符,将 s 切分成多个子切片,结果中包含 sep 本身
// 如果 sep 为空,则将 s 切分成 unicode 字符列表。
// 如果 s 中没有 sep 子串,则将整个 s 作为 []string 的第一个元素返回
func splitafter(s, sep string) []string
func main() {
 s := "hello, 世界! hello!"
 ss := strings.splitafter(s, " ")
 fmt.printf("%q\n", ss) // ["hello, " "世界! " "hello!"]
 ss = strings.splitafter(s, ", ")
 fmt.printf("%q\n", ss) // ["hello, " "世界! hello!"]
 ss = strings.splitafter(s, "")
 fmt.printf("%q\n", ss) // 单个字符列表
}

------------------------------------------------------------

// fields 以连续的空白字符为分隔符,将 s 切分成多个子串,结果中不包含空白字符本身
// 空白字符有:\t, \n, \v, \f, \r, ' ', u+0085 (nel), u+00a0 (nbsp)
// 如果 s 中只包含空白字符,则返回一个空列表
func fields(s string) []string

func main() {
 s := "hello, 世界! hello!"
 ss := strings.fields(s)
 fmt.printf("%q\n", ss) // ["hello," "世界!" "hello!"]
}

------------------------------------------------------------

// fieldsfunc 以一个或多个满足 f(rune) 的字符为分隔符,
// 将 s 切分成多个子串,结果中不包含分隔符本身。
// 如果 s 中没有满足 f(rune) 的字符,则返回一个空列表。
func fieldsfunc(s string, f func(rune) bool) []string

func isslash(r rune) bool {
 return r == '\\' || r == '/'
}

func main() {
 s := "c:\\windows\\system32\\filename"
 ss := strings.fieldsfunc(s, isslash)
 fmt.printf("%q\n", ss) // ["c:" "windows" "system32" "filename"]
}

------------------------------------------------------------

// join 将 a 中的子串连接成一个单独的字符串,子串之间用 sep 分隔
func join(a []string, sep string) string
func main() {
 ss := []string{"monday", "tuesday", "wednesday"}
 s := strings.join(ss, "|")
 fmt.println(s)
}

------------------------------------------------------------

// hasprefix 判断字符串 s 是否以 prefix 开头
func hasprefix(s, prefix string) bool

func main() {
 s := "hello 世界!"
 b := strings.hasprefix(s, "hello")
 fmt.println(b) // false
 b = strings.hasprefix(s, "hello")
 fmt.println(b) // true
}

------------------------------------------------------------

// hassuffix 判断字符串 s 是否以 prefix 结尾
func hassuffix(s, suffix string) bool
func main() {
 s := "hello 世界!"
 b := strings.hassuffix(s, "世界")
 fmt.println(b) // false
 b = strings.hassuffix(s, "世界!")
 fmt.println(b) // true
}

------------------------------------------------------------

// map 将 s 中满足 mapping(rune) 的字符替换为 mapping(rune) 的返回值。
// 如果 mapping(rune) 返回负数,则相应的字符将被删除。
func map(mapping func(rune) rune, s string) string

func slash(r rune) rune {
 if r == '\\' {
  return '/'
 }
 return r
}
func main() {

 s := "c:\\windows\\system32\\filename"
 ms := strings.map(slash, s)
 fmt.printf("%q\n", ms) // "c:/windows/system32/filename"
}

-----------------------------------------------------------

// repeat 将 count 个字符串 s 连接成一个新的字符串
func repeat(s string, count int) string
func main() {
 s := "hello!"
 rs := strings.repeat(s, 3)
 fmt.printf("%q\n", rs) // "hello!hello!hello!"
}

------------------------------------------------------------

// toupper 将 s 中的所有字符修改为其大写格式
// 对于非 ascii 字符,它的大写格式需要查表转换
func toupper(s string) string

// tolower 将 s 中的所有字符修改为其小写格式
// 对于非 ascii 字符,它的小写格式需要查表转换
func tolower(s string) string

// totitle 将 s 中的所有字符修改为其 title 格式
// 大部分字符的 title 格式就是其 upper 格式
// 只有少数字符的 title 格式是特殊字符
// 这里的 totitle 主要给 title 函数调用
func totitle(s string) string
func main() {
 s := "hello world abc"
 us := strings.toupper(s)
 ls := strings.tolower(s)
 ts := strings.totitle(s)
 fmt.printf("%q\n", us) // "hello world abc"
 fmt.printf("%q\n", ls) // "hello world abc"
 fmt.printf("%q\n", ts) // "hello world abc"
}

// 获取非 ascii 字符的 title 格式列表
func main() {
 for _, cr := range unicode.caseranges {
  // u := uint32(cr.delta[unicode.uppercase]) // 大写格式
  // l := uint32(cr.delta[unicode.lowercase]) // 小写格式
  t := uint32(cr.delta[unicode.titlecase]) // title 格式
  // if t != 0 && t != u {
  if t != 0 {
   for i := cr.lo; i <= cr.hi; i++ {
    fmt.printf("%c -> %c\n", i, i+t)
   }
  }
 }
}

------------------------------------------------------------

// toupperspecial 将 s 中的所有字符修改为其大写格式。
// 优先使用 _case 中的规则进行转换
func toupperspecial(_case unicode.specialcase, s string) string

// tolowerspecial 将 s 中的所有字符修改为其小写格式。
// 优先使用 _case 中的规则进行转换
func tolowerspecial(_case unicode.specialcase, s string) string

// totitlespecial 将 s 中的所有字符修改为其 title 格式。
// 优先使用 _case 中的规则进行转换
func totitlespecial(_case unicode.specialcase, s string) string

_case 规则说明,以下列语句为例:
unicode.caserange{'a', 'z', [unicode.maxcase]rune{3, -3, 0}}
·其中 'a', 'z' 表示此规则只影响 'a' 到 'z' 之间的字符。
·其中 [unicode.maxcase]rune 数组表示:
当使用 toupperspecial 转换时,将字符的 unicode 编码与第一个元素值(3)相加
当使用 tolowerspecial 转换时,将字符的 unicode 编码与第二个元素值(-3)相加
当使用 totitlespecial 转换时,将字符的 unicode 编码与第三个元素值(0)相加

func main() {
 // 定义转换规则
 var _mycase = unicode.specialcase{
  // 将半角逗号替换为全角逗号,totitle 不处理
  unicode.caserange{',', ',',
   [unicode.maxcase]rune{',' - ',', ',' - ',', 0}},
  // 将半角句号替换为全角句号,totitle 不处理
  unicode.caserange{'.', '.',
   [unicode.maxcase]rune{'。' - '.', '。' - '.', 0}},
  // 将 abc 分别替换为全角的 abc、abc,totitle 不处理
  unicode.caserange{'a', 'c',
   [unicode.maxcase]rune{'a' - 'a', 'a' - 'a', 0}},
 }
 s := "abcdef,abcdef."
 us := strings.toupperspecial(_mycase, s)
 fmt.printf("%q\n", us) // "abcdef,abcdef。"
 ls := strings.tolowerspecial(_mycase, s)
 fmt.printf("%q\n", ls) // "abcdef,abcdef。"
 ts := strings.totitlespecial(_mycase, s)
 fmt.printf("%q\n", ts) // "abcdef,abcdef."
}

------------------------------------------------------------

// title 将 s 中的所有单词的首字母修改为其 title 格式
// bug: title 规则不能正确处理 unicode 标点符号
func title(s string) string
func main() {
 s := "hello world"
 ts := strings.title(s)
 fmt.printf("%q\n", ts) // "hello world"
}

------------------------------------------------------------

// trimleftfunc 将删除 s 头部连续的满足 f(rune) 的字符
func trimleftfunc(s string, f func(rune) bool) string

------------------------------------------------------------

// trimrightfunc 将删除 s 尾部连续的满足 f(rune) 的字符
func trimrightfunc(s string, f func(rune) bool) string
func isslash(r rune) bool {
 return r == '\\' || r == '/'
}

func main() {
 s := "\\\\hostname\\c\\windows\\"
 ts := strings.trimrightfunc(s, isslash)
 fmt.printf("%q\n", ts) // "\\\\hostname\\c\\windows"
}

------------------------------------------------------------

// trimfunc 将删除 s 首尾连续的满足 f(rune) 的字符
func trimfunc(s string, f func(rune) bool) string

func isslash(r rune) bool {
    return r == '\\' || r == '/'
}
func main() {
    s := "\\\\hostname\\c\\windows\\"
    ts := strings.trimfunc(s, isslash)
    fmt.printf("%q\n", ts) // "hostname\\c\\windows"
}

------------------------------------------------------------

// 返回 s 中第一个满足 f(rune) 的字符的字节位置。
// 如果没有满足 f(rune) 的字符,则返回 -1
func indexfunc(s string, f func(rune) bool) int
func isslash(r rune) bool {
 return r == '\\' || r == '/'
}

func main() {
 s := "c:\\windows\\system32"
 i := strings.indexfunc(s, isslash)
 fmt.printf("%v\n", i) // 2
}

------------------------------------------------------------

// 返回 s 中最后一个满足 f(rune) 的字符的字节位置。
// 如果没有满足 f(rune) 的字符,则返回 -1
func lastindexfunc(s string, f func(rune) bool) int

func isslash(r rune) bool {
 return r == '\\' || r == '/'
}

func main() {
 s := "c:\\windows\\system32"
 i := strings.lastindexfunc(s, isslash)
 fmt.printf("%v\n", i) // 10
}

------------------------------------------------------------

// trim 将删除 s 首尾连续的包含在 cutset 中的字符
func trim(s string, cutset string) string

func main() {
 s := " hello 世界! "
 ts := strings.trim(s, " helo!")
 fmt.printf("%q\n", ts) // "世界"
}

------------------------------------------------------------

// trimleft 将删除 s 头部连续的包含在 cutset 中的字符
func trimleft(s string, cutset string) string

func main() {
 s := " hello 世界! "
 ts := strings.trimleft(s, " helo")
 fmt.printf("%q\n", ts) // "世界! "
}

------------------------------------------------------------

// trimright 将删除 s 尾部连续的包含在 cutset 中的字符
func trimright(s string, cutset string) string

func main() {
 s := " hello 世界! "
 ts := strings.trimright(s, " 世界!")
 fmt.printf("%q\n", ts) // " hello"
}

------------------------------------------------------------

// trimspace 将删除 s 首尾连续的的空白字符
func trimspace(s string) string
func main() {
 s := " hello 世界! "
 ts := strings.trimspace(s)
 fmt.printf("%q\n", ts) // "hello 世界!"
}

------------------------------------------------------------

// trimprefix 删除 s 头部的 prefix 字符串
// 如果 s 不是以 prefix 开头,则返回原始 s
func trimprefix(s, prefix string) string

func main() {
 s := "hello 世界!"
 ts := strings.trimprefix(s, "hello")
 fmt.printf("%q\n", ts) // " 世界"
}

------------------------------------------------------------

// trimsuffix 删除 s 尾部的 suffix 字符串
// 如果 s 不是以 suffix 结尾,则返回原始 s
func trimsuffix(s, suffix string) string
func main() {
 s := "hello 世界!!!!!"
 ts := strings.trimsuffix(s, "!!!!")
 fmt.printf("%q\n", ts) // " 世界"
}

注:trimsuffix只是去掉s字符串结尾的suffix字符串,只是去掉1次,而trimright是一直去掉s字符串右边的字符串,只要有响应的字符串就去掉,是一个多次的过程,这也是二者的本质区别.
------------------------------------------------------------

// replace 返回 s 的副本,并将副本中的 old 字符串替换为 new 字符串
// 替换次数为 n 次,如果 n 为 -1,则全部替换
// 如果 old 为空,则在副本的每个字符之间都插入一个 new
func replace(s, old, new string, n int) string

func main() {
 s := "hello 世界!"
 s = strings.replace(s, " ", ",", -1)
 fmt.println(s)
 s = strings.replace(s, "", "|", -1)
 fmt.println(s)
}

------------------------------------------------------------

// equalfold 判断 s 和 t 是否相等。忽略大小写,同时它还会对特殊字符进行转换
// 比如将“ϕ”转换为“φ”、将“DŽ”转换为“Dž”等,然后再进行比较
func equalfold(s, t string) bool
func main() {
 s1 := "hello 世界! ϕ DŽ"
 s2 := "hello 世界! φ Dž"
 b := strings.equalfold(s1, s2)
 fmt.printf("%v\n", b) // true
}

============================================================

// reader.go

------------------------------------------------------------

// reader 结构通过读取字符串,实现了 io.reader,io.readerat,
// io.seeker,io.writerto,io.bytescanner,io.runescanner 接口
type reader struct {
s string // 要读取的字符串
i int // 当前读取的索引位置,从 i 处开始读取数据
prevrune int // 读取的前一个字符的索引位置,小于 0 表示之前未读取字符
}

// 通过字符串 s 创建 strings.reader 对象
// 这个函数类似于 bytes.newbufferstring
// 但比 bytes.newbufferstring 更有效率,而且只读
func newreader(s string) *reader { return &reader{s, 0, -1} }

------------------------------------------------------------

// len 返回 r.i 之后的所有数据的字节长度
func (r *reader) len() int

func main() {
 s := "hello 世界!"
 // 创建 reader
 r := strings.newreader(s)
 // 获取字符串的编码长度
 fmt.println(r.len()) // 13
}

------------------------------------------------------------

// read 将 r.i 之后的所有数据写入到 b 中(如果 b 的容量足够大)
// 返回读取的字节数和读取过程中遇到的错误
// 如果无可读数据,则返回 io.eof
func (r *reader) read(b []byte) (n int, err error)

func main() {
 s := "hello world!"
 // 创建 reader
 r := strings.newreader(s)
 // 创建长度为 5 个字节的缓冲区
 b := make([]byte, 5)
 // 循环读取 r 中的字符串
 for n, _ := r.read(b); n > 0; n, _ = r.read(b) {
  fmt.printf("%q, ", b[:n]) // "hello", " worl", "d!"
 }
}

------------------------------------------------------------

// readat 将 off 之后的所有数据写入到 b 中(如果 b 的容量足够大)
// 返回读取的字节数和读取过程中遇到的错误
// 如果无可读数据,则返回 io.eof
// 如果数据被一次性读取完毕,则返回 io.eof
func (r *reader) readat(b []byte, off int64) (n int, err error)

func main() {
 s := "hello world!"
 // 创建 reader
 r := strings.newreader(s)
 // 创建长度为 5 个字节的缓冲区
 b := make([]byte, 5)
 // 读取 r 中指定位置的字符串
 n, _ := r.readat(b, 0)
 fmt.printf("%q\n", b[:n]) // "hello"
 // 读取 r 中指定位置的字符串
 n, _ = r.readat(b, 6)
 fmt.printf("%q\n", b[:n]) // "world"
}

------------------------------------------------------------

// readbyte 将 r.i 之后的一个字节写入到返回值 b 中
// 返回读取的字节和读取过程中遇到的错误
// 如果无可读数据,则返回 io.eof
func (r *reader) readbyte() (b byte, err error)
func main() {
 s := "hello world!"
 // 创建 reader
 r := strings.newreader(s)
 // 读取 r 中的一个字节
 for i := 0; i < 3; i++ {
  b, _ := r.readbyte()
  fmt.printf("%q, ", b) // 'h', 'e', 'l',
 }
}

------------------------------------------------------------

// unreadbyte 撤消前一次的 readbyte 操作,即 r.i--
func (r *reader) unreadbyte() error
func main() {
 s := "hello world!"
 // 创建 reader
 r := strings.newreader(s)
 // 读取 r 中的一个字节
 for i := 0; i < 3; i++ {
  b, _ := r.readbyte()
  fmt.printf("%q, ", b) // 'h', 'h', 'h',
  r.unreadbyte()        // 撤消前一次的字节读取操作
 }
}

------------------------------------------------------------

// readrune 将 r.i 之后的一个字符写入到返回值 ch 中
// ch: 读取的字符
// size:ch 的编码长度
// err: 读取过程中遇到的错误
// 如果无可读数据,则返回 io.eof
// 如果 r.i 之后不是一个合法的 utf-8 字符编码,则返回 utf8.runeerror 字符
func (r *reader) readrune() (ch rune, size int, err error)

func main() {
 s := "你好 世界!"
 // 创建 reader
 r := strings.newreader(s)
 // 读取 r 中的一个字符
 for i := 0; i < 5; i++ {
  b, n, _ := r.readrune()
  fmt.printf(`"%c:%v", `, b, n)
  // "你:3", "好:3", " :1", "世:3", "界:3",
 }
}

------------------------------------------------------------

// 撤消前一次的 readrune 操作
func (r *reader) unreadrune() error

func main() {
 s := "你好 世界!"
 // 创建 reader
 r := strings.newreader(s)
 // 读取 r 中的一个字符
 for i := 0; i < 5; i++ {
  b, _, _ := r.readrune()
  fmt.printf("%q, ", b)
  // '你', '你', '你', '你', '你',
  r.unreadrune() // 撤消前一次的字符读取操作
 }
}

------------------------------------------------------------

// seek 用来移动 r 中的索引位置
// offset:要移动的偏移量,负数表示反向移动
// whence:从那里开始移动,0:起始位置,1:当前位置,2:结尾位置
// 如果 whence 不是 0、1、2,则返回错误信息
// 如果目标索引位置超出字符串范围,则返回错误信息
// 目标索引位置不能超出 1 << 31,否则返回错误信息
func (r *reader) seek(offset int64, whence int) (int64, error)

func main() {
 s := "hello world!"
 // 创建 reader
 r := strings.newreader(s)
 // 创建读取缓冲区
 b := make([]byte, 5)
 // 读取 r 中指定位置的内容
 r.seek(6, 0) // 移动索引位置到第 7 个字节
 r.read(b)    // 开始读取
 fmt.printf("%q\n", b)
 r.seek(-5, 1) // 将索引位置移回去
 r.read(b)     // 继续读取
 fmt.printf("%q\n", b)
}

------------------------------------------------------------

// writeto 将 r.i 之后的数据写入接口 w 中
func (r *reader) writeto(w io.writer) (n int64, err error)

func main() {
 s := "hello world!"
 // 创建 reader
 r := strings.newreader(s)
 // 创建 bytes.buffer 对象,它实现了 io.writer 接口
 buf := bytes.newbuffer(nil)
 // 将 r 中的数据写入 buf 中
 r.writeto(buf)
 fmt.printf("%q\n", buf) // "hello world!"
}

============================================================

// replace.go

------------------------------------------------------------

// replacer 根据一个替换列表执行替换操作
type replacer struct {
replace(s string) string
writestring(w io.writer, s string) (n int, err error)
}

------------------------------------------------------------

// newreplacer 通过“替换列表”创建一个 replacer 对象。
// 按照“替换列表”中的顺序进行替换,只替换非重叠部分。
// 如果参数的个数不是偶数,则抛出异常。
// 如果在“替换列表”中有相同的“查找项”,则后面重复的“查找项”会被忽略
func newreplacer(oldnew ...string) *replacer

------------------------------------------------------------

// replace 返回对 s 进行“查找和替换”后的结果
// replace 使用的是 boyer-moore 算法,速度很快
func (r *replacer) replace(s string) string

func main() {
 srp := strings.newreplacer("hello", "你好", "world", "世界", "!", "!")
 s := "hello world!hello world!hello world!"
 rst := srp.replace(s)
 fmt.print(rst) // 你好 世界!你好 世界!hello world!
}
<span style="color:#ff0000;">注:这两种写法均可.</span>
func main() {

 wl := []string{"hello", "hi", "hello", "你好"}
 srp := strings.newreplacer(wl...)
 s := "hello world! hello world! hello world!"
 rst := srp.replace(s)
 fmt.print(rst) // hi world! hi world! hello world!
}

------------------------------------------------------------

// writestring 对 s 进行“查找和替换”,然后将结果写入 w 中
func (r *replacer) writestring(w io.writer, s string) (n int, err error)

func main() {
 wl := []string{"hello", "你好", "world", "世界", "!", "!"}
 srp := strings.newreplacer(wl...)
 s := "hello world!hello world!hello world!"
 srp.writestring(os.stdout, s)
 // 你好 世界!你好 世界!hello world!
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网