在这里仅仅总结一些常用的方法,更多方法请参考 https://studygolang.com/pkgdoc

以下函数均在strings包里面

  1. Contains: 判断一个字符串是否在另外一个字符串中。
  2. Join: 字符串连接
  3. Index :在一个字符串中查找某个字符串的位置
  4. Repeat: 某个字符串重复多少次,返回的是重复后的字符串
  5. Replace : 在s字符串中,把 old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换

下面是用法举例

第一个函数Contains的用法

	var str string = "hello"
	b := strings.Contains(str,"go")
	fmt.Println(b)

第二个 func Join(a []string, sep string) string

	s := []string{"abc","hello","world"}
	str := strings.Join(s,"|")//将上面三个字符串用‘|’链接起来
	fmt.Println((str))

第三个 func Index(s, sep string) int

	str := "andyHello"
	n:=strings.Index(str,"andy") //判断 andy在str中出现的位置,从0开始计算
	fmt.Println(n)

第四个 func Repeat(s string, count int) string

	str := strings.Repeat("andy",3)//将字符串"andy"重复3次
	fmt.Println(str)

第五个 func Replace(s string, old string, new string, n int) string
返回将s中前n个不重叠old子串都替换为new的新字符串,如果n<0会替换所有old子串, n>0时代表替换次数

	str := "hello andy"
	strNew :=strings.Replace(str,"ll","w",1)  //将"ll"字符串替换为"w"
	fmt.Println(strNew)

第六个 func Split(s string, sep string) []string

用去掉s中出现的 sep 的方式进行分割,会分割到结尾,并返回生成的所有片段组成的切片(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。如果sep为空字符,Split会将s切分成每一个unicode码值一个字符串。

	str := "hello@world@itcast"
	s:= strings.Split(str,"@")
	fmt.Println(s)

字符串的转化

所用到的函数在strconv包内

  1. FormatBool (b bool) 将bool类型转化为字符串类型
  2. Itoa(n int)将整型类型转换为string
  3. ParseInt(s string, base int, bitSize int) (i int64, err error) 将字符串类型转换为布尔类型 返回两个