1 package main
2
3 import (
4 "fmt"
5 "strings"
6 )
7
8 func main() {
9 /*
10 strings包下的关于字符串的函数
11
12 */
13
14 s1 := "helloworld"
15 // 1.是否包含指定的内容-->bool
16 fmt.Println(strings.Contains(s1, "abc")) // false
17 // 2.是否包含chars中任意的一个字符即可
18 fmt.Println(strings.ContainsAny(s1, "abcd")) // true
19 // 3.统计substr在s中出现的次数
20 fmt.Println(strings.Count(s1, "lloo")) // 0
21
22 // 4.以xxx前缀开头,以xxx后缀结尾
23 s2 := "20190525课堂笔记.txt"
24 if strings.HasPrefix(s2, "201905") {
25 fmt.Println("19年5月的文件。。")
26 }
27 if strings.HasSuffix(s2, ".txt") {
28 fmt.Println("文本文档。。")
29 }
30
31 // 索引
32 // helloworld
33 fmt.Println(strings.Index(s1, "lloo")) // 查找substr在s中的位置,如果不存在就返回-1 -1
34 fmt.Println(strings.IndexAny(s1, "abcdh")) // 查找chars中任意的一个字符,出现在s中的位置 0
35 fmt.Println(strings.LastIndex(s1, "l")) // 查找substr在s中最后一次出现的位置 8
36
37 // 字符串的拼接
38 ss1 := []string{"abc", "world", "hello", "ruby"}
39 s3 := strings.Join(ss1, "-")
40 fmt.Println(s3) // abc-world-hello-ruby
41
42 // 切割
43 s4 := "123,4563,aaa,49595,45"
44 ss2 := strings.Split(s4, ",")
45 fmt.Println(ss2) // [123 4563 aaa 49595 45]
46 for i := 0; i < len(ss2); i++ {
47 fmt.Println(ss2[i])
48 }
49
50 // 重复,自己拼接自己count次
51 s5 := strings.Repeat("hello", 5)
52 fmt.Println(s5) // hellohellohellohellohello
53
54 // 替换
55 // helloworld
56 s6 := strings.Replace(s1, "l", "*", -1)
57 fmt.Println(s6) // he**owor*d
58
59 s7 := "heLLo WOrlD**123.."
60 fmt.Println(strings.ToLower(s7)) // hello world**123..
61 fmt.Println(strings.ToUpper(s7)) // HELLO WORLD**123..
62
63 /*
64 截取子串:
65 substring(start,end)-->substr
66 str[start:end]-->substr
67 包含start,不包含end下标
68 */
69
70 fmt.Println(s1) // helloworld
71 s8 := s1[:5] //
72 fmt.Println(s8) // hello
73 fmt.Println(s1[5:]) // world
74 }