Go 字符串常用函数。Contains()、Join()、Index()、Repeat()、Replace()、Split()、Trim()、Fields()

demo.go(字符串常用函数):

package main

import (
	"fmt"
	"strings"
)

func main() {
	// Contains() 字符串是否包含
	b := strings.Contains("hello world","llo")
	fmt.Println(b)  // true

	// Join() 将字符串切片进行拼接
	slice := []string{"aa","bb","cc"}
	str := strings.Join(slice,"--")
	fmt.Println(str)  // aa--bb--cc

	// Index() 查找并返回下标(查找到的第一个,-1表示未找到)
	ind := strings.Index("hello world","llo")  // 返回int类型(下标)
	fmt.Println(ind)  // 2

	// Repeat() 字符串重复
	str2 := strings.Repeat("abc",3)  // 3表示重复3次
	fmt.Println(str2)  // abcabcabc

	// Replace() 字符串替换
	str3 := strings.Replace("hello hello hello", "el","YY",2) // 2表示替换2次,-1全部替换
	fmt.Println(str3)  // hYYlo hYYlo hello

	// Split() 字符串分割
	slice2 := strings.Split("-hello-world-haha-","-")  // 返回字符串切片 []string
	fmt.Println(slice2)  // [ hello world haha ]  (两端有两个空元素)
	fmt.Println(len(slice2))  // 5

	// Trim() 去掉字符串两端空格
	str4 := strings.Trim("   hello world   "," ")
	fmt.Println(str4)  // hello world

	// Fields() 用空格分割字符串,返回字符串切片
	slice3 := strings.Fields(" aa bb cc ")  // 返回字符串切片 []string
	fmt.Println(slice3)  // [aa bb cc]
	fmt.Println(len(slice3))  // 3
}

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/88655540