Skip to content

Latest commit

 

History

History
115 lines (81 loc) · 2.76 KB

File metadata and controls

115 lines (81 loc) · 2.76 KB

7.6 字符串处理

7.6.1 字符串操作

常用的函数:

  • func Contains(s, substr string) bool

    判断s中是否包含substr

	fmt.Println(strings.Contains("seafood", "foo")) //true
	fmt.Println(strings.Contains("seafood", "far"))//fasle
	fmt.Println(strings.Contains("seafood", ""))//true
	fmt.Println(strings.Contains("", ""))//true
  • func Join(a []string, sep string) string

    将slice的字符串通过分隔符sep连接

ss := []string{"A", "B", "C"}
fmt.Println(strings.Join(ss, ":"))//A:B:C
  • func Index(s, sep string) int

    在s中查找sep的位置,找不到返回-1

fmt.Println(strings.Index("chiken", "ken"))//3
fmt.Println(strings.Index("chiken", "car"))//-1
  • func Repeat(s string, count int) string

    重复s count 次,并返回

fmt.Println("ba" + strings.Repeat("na", 2))//banana
  • func Replace(s, old, new string, n int) string 在s中将old使用new进行替换,n为替换次数,当n<0时表示全部替换
	fmt.Println(strings.Replace("banana", "a", "k", 1))//bknana
	fmt.Println(strings.Replace("banana", "a", "k", -1))//bknknk
	fmt.Println(strings.Replace("banana", "a", "k", 0))//banana
  • func Split(s, sep string) []string

    将s按照sep进行分割

	fmt.Printf("%q\n", strings.Split("A B C ", " "))//["A" "B" "C" ""]
	fmt.Printf("%q\n", strings.Split("A B C ", ""))//["A" " " "B" " " "C" " "]
	fmt.Printf("%q\n", strings.Split("AaBaCa", "a"))//["A" "B" "C" ""]
	fmt.Printf("%q\n", strings.Split("", "abc"))//[""]
  • func Trim(s string, cutset string) string

    在字符串头尾去除cutset

	fmt.Printf("%q", strings.Trim("!!Hello!!", "!"))//"Hello"
  • func Fields(s string) []string

    去除s中的空格符,并按照空格符分割

	fmt.Printf("%q\n", strings.Fields("A B C"))//["A" "B" "C"]

7.6.2 字符串转换

常用的函数:

  • Append 系列函数将T转换为字符串后添加到现有的[]byte中
	b := make([]byte, 0, 1024)
	b = strconv.AppendInt(b, 120, 10)
	b = strconv.AppendBool(b, false)
	b = strconv.AppendQuote(b, "ABC")
	b = strconv.AppendQuoteRune(b, '字')
	fmt.Printf("%q", string(b))//"120false\"ABC\"'字'"
  • Format 系列函数将T转换为字符串
	fmt.Printf("%q\n", strconv.FormatBool(true))//"true"
	fmt.Printf("%q\n", strconv.FormatInt(-120, 16))//"-78"
	fmt.Printf("%q\n", strconv.FormatFloat(12.12, 'g', 4, 64))//"12.12"
	fmt.Printf("%q\n", strconv.FormatUint(100, 8))//"144"
	fmt.Printf("%q\n", strconv.Itoa(1000))//"1000"
  • Parse 系列函数将字符串转化成T
	s1, _ := strconv.ParseBool("false")
	s2, _ := strconv.ParseFloat("12.12", 64)
	s3, _ := strconv.ParseInt("-123", 10, 64)
	s4, _ := strconv.ParseUint("111", 2, 64)
	s5, _ := strconv.Atoi("100")
	fmt.Println(s1, s2, s3, s4, s5)//false 12.12 -123 7 100