15、string

我也有梦想呀 / 2023-05-03 / 原文

1.string是什么?

Go中的字符串是一个字节的切片,可以通过将其内容封装起在""中来创建字符串。Go中的的字符串是Unicode兼容的并且是UTF-8编码的。

2.string的使用


3.strings:字符串的常用函数

s5 := `hello world`

	// 判断指定的字符串是否存在
	b1 := strings.Contains(s5, "hel")
	fmt.Println("b1:", b1)

	// 判断指定的字符串任意一个字符是否存在
	b2 := strings.ContainsAny(s5, "abc")
	fmt.Println("b2:", b2)

	// 统计指定的字符串出现的个数
	count := strings.Count(s5, "wo")
	fmt.Println("count:", count)

	// 判断字符串是否以指定的字符串开头
	prefix := strings.HasPrefix(s5, "ld")
	fmt.Println("prefix:", prefix)

	// 判断字符串是否以指定的字符串结尾
	suffix := strings.HasSuffix(s5, "he")
	fmt.Println("suffix:", suffix)

	// 获取指定字符串首次出现的索引位置
	index := strings.Index(s5, "l")
	fmt.Println("index:", index)

	// 获取指定字符串最后一次出现的索引位置
	lastIndex := strings.LastIndex(s5, "o")
	fmt.Println("lastIndex:", lastIndex)

	// 字符串拼接
	sArr := []string{"he", "llo", "wo", "rld"}
	join := strings.Join(sArr, "-")
	fmt.Println(join)

	// 字符串切割
	s6 := "123abcABC你好中国"
	split := strings.Split(s6, "")
	for _, v := range split {
		fmt.Println(v)
	}

	// 将指定的字符串重复拼接n次
	repeat := strings.Repeat("hello", 5)
	fmt.Println(repeat)

	// 替换;n:指定替换的字符个数,-1全替换
	replace := strings.Replace(s5, "l", "*", 1)
	replace2 := strings.Replace(s5, "l", "*", -1)
	fmt.Println(replace)
	fmt.Println(replace2)

	// 大小写转换
	lower := strings.ToLower(s5)
	upper := strings.ToUpper(s5)
	fmt.Println(lower)
	fmt.Println(upper)

	/**
	截取子字符串 类似Java语言中的substring
	*/
	s9 := "我是中国人"
	subStr := s9[6:]
	fmt.Println(subStr)