欢迎光临散文网 会员登陆 & 注册

Go 标准包 strings 学习(7)Map,Repeat,Replace

2023-05-15 13:04 作者:取悦疾风  | 我要投稿

上次标题太长了,后面的一个方法名没写出来,但是标题还是要写的,无非就是少写几个方法

后面就先给文章一个目录吧

本次学习了

Map,Repeat,Replace

开始

https://pkg.go.dev/strings@go1.20.4#Map


func Map

Map returns a copy of the string s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.

Map返回字符串s的副本,其中所有字符都根据映射函数进行了修改。如果映射返回负值,则从字符串中删除该字符,不进行替换。

没看懂...

例子

输出

'Gjnf oevyyvt naq gur fyvgul tbcure...

理解

案例里面演示了一个类似加密的操作

这个方法的应用暂时没想到

func Repeat

Repeat returns a new string consisting of count copies of the string s.

It panics if count is negative or if the result of (len(s) * count) overflows.

Repeat返回一个由字符串s的count个副本组成的新字符串。

如果count为负或(len(s) * count)的结果溢出,则会产生恐慌。

举例

输出

banana

理解

就是复制count次,然后组装成1个新的字符串

func Replace

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

Replace返回字符串s的副本,其中旧的前n个不重叠的实例替换为new。如果old为空,它匹配字符串的开头和每个UTF-8序列之后,为k-rune字符串产生最多k+1个替换。如果n < 0,则替换次数没有限制。

案例

输出

oinky oinky oink

moo moo moo

理解

就是在s里面把old的替换成new字符串,可以指定替换多少个,要换多少n就写多少,如果要全替换就写-1

Go 标准包 strings 学习(7)Map,Repeat,Replace的评论 (共 条)

分享到微博请遵守国家法律