s1 := "helloworld"
//1.是否包含指定的内容--》bool
fmt.Println(strings.Contains(s1, "woc"))//false
//2.是否包含chars中任意的一个字符即可
fmt.Println(strings.ContainsAny(s1, "abcd"))//true
//3.统计substr在s中出现的次数
fmt.Println(strings.Count(s1, "llo"))//1
s2 := "20190525课堂笔记.txt"
//判断以什么前缀开头
if strings.HasPrefix(s2, "201905") {
fmt.Println("19年5月的文件")
}
//判断以什么后缀结尾
if strings.HasSuffix(s2, ".txt") {
fmt.Println("文本文档..")
}
//helloworld
//查找substr在s中的位置,如果不存在就返回-1
fmt.Println(strings.Index(s1, "or")) //6
//查找chars中任意的一个字符,出现在s中的位置
fmt.Println(strings.IndexAny(s1, "abcd"))//9
//查找substr在s中最后一次出现的位置
fmt.Println(strings.LastIndex(s1, "l")) //8
//字符串的拼接
ss1 := []string{"abc","world","hello","ruby"}
s3 := strings.Join(ss1, "-")
fmt.Println(s3) //abc-world-hello-ruby
//切割
s4 := "123,4563,aaa,49595,45"
ss2 := strings.Split(s4, ",")
fmt.Printf("%T\n", ss2) //[]string
fmt.Println(ss2) //[123 4563 aaa 49595 45]
for i := 0; i < len(ss2); i++ {
fmt.Println(ss2[i])
}
//重复,自己拼接自己count次
s5 := strings.Repeat("hello", 5)
fmt.Println(s5) //hellohellohellohellohello
//替换
s6 := strings.Replace(s1, "l", "*", -1)
fmt.Println(s6) //he**owor*d
s7 := "heLLo worlD**123.."
//所有转小写
fmt.Println(strings.ToLower(s7)) //hello world**123..
//所有转大写
fmt.Println(strings.ToUpper(s7)) //HELLO WORLD**123..
//截取子串 str(start,end) -> substr 与数组,切片类似
fmt.Println(s1) //helloworld
s17 := s1[2:4]//左闭区间,包含左边的下标,不包含右边的
fmt.Println(s17) //ll
s8 := s1[:5]
fmt.Println(s8) //hello
fmt.Println(s1[5:]) //world
字符串函数
最新推荐文章于 2025-06-14 21:08:09 发布