风离不摆烂学习日志 Day10 Go 字符串常用操作

image-20221128231447712

Contains

func Contains(s, substr string) bool
功能:字符串s中是否包含substr,返回bool值

Join

func Join(a []string, sep string) string
功能:字符串链接,把slice a通过sep链接起来

Index

func Index(s, sep string) int
功能:在字符串s中查找sep所在的位置,返回位置值,找不到返回-1

Repeat

func Repeat(s string, count int) string
功能:重复s字符串count次,最后返回重复的字符串

Replace

func Replace(s, old, new string, n int) string
功能:在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换

Split

func Split(s, sep string) []string
功能:把s字符串按照sep分割,返回slice

Trim

func Trim(s string, cutset string) string
功能:在s字符串的头部和尾部去除cutset指定的字符串

Fields

func Fields(s string) []string
功能:去除s字符串的空格符,并且按照空格分割返回slice

package main

import (
	"fmt"
	"strings"
)

func main() {
	//"hellogo"中是否包含"hello",包含返回true,不包含返回false
	fmt.Println(strings.Contains("hellogo", "hello"))
	fmt.Println(strings.Contains("hellogo", "abc"))
	fmt.Println("===================================================")
	//Join 将内容组合在一起
	s := []string{"abc", "hello", "eryajf", "go"}
	jo := strings.Join(s, "--") //"&"表示以&作为分隔符
	fmt.Println("jo = ", jo)
	fmt.Println("===================================================")
	//Index,查找字符串的位置
	fmt.Println(strings.Index("abchello", "hello"))
	fmt.Println(strings.Index("abchello", "go")) //不包含返回-1

	fmt.Println("===================================================")
	//Repeat:重复s字符串count次,最后返回重复的字符串
	buf := strings.Repeat("go", 3)
	fmt.Println("buf = ", buf)
	fmt.Println("===================================================")
	//Replace
	fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))         //表示把k更换成ky,更换两次
	fmt.Println(strings.Replace("oink oink oink", "oink", "eryajf", -1)) //小于0表示全部替换
	fmt.Println("===================================================")
	//Split 以指定的分隔符拆分
	s1 := strings.Split("hello@abc@eryajf@go", "@")
	fmt.Println("s1 = ", s1)
	fmt.Println("===================================================")
	//Trim去掉两头的字符
	s2 := strings.Trim("   are u ok ?    ", " ") //去掉两头的空格
	fmt.Printf("s2 = #%s#\n", s2)
	fmt.Println("===================================================")
	//Fields去掉空格,把元素放入切片中
	s3 := strings.Fields("   are u ok ?    ")
	for i, data := range s3 {
		fmt.Println(i, ",", data)
	}
}

image-20221128231352433