按单个/多个字符分割字符串
按指定内容切割字符串
str := "hello world"res0 :=strings.Split(str,"w")fmt.Println(res0)//[hello orld]
字符串str以;结尾进行分割
str := "hello;world;"res1 := strings.SplitAfter(str,";")//[hello; world; ]fmt.Println(res1)
判断str中是否包含某字符串
返回bool类型,没有时为false
str := "hello world"fmt.Println(strings.Contains(str, "lo"), strings.Contains(str, "t")) //true false
判断是否以某个字符串开头/结尾
str := "hello world"//以某个字符串开始i := strings.HasPrefix(str, "h")j := strings.HasPrefix(str, "t")fmt.Println(i, j) //true false//以某个字符串结尾i1 := strings.HasSuffix(str, "h")j1 := strings.HasSuffix(str, "d") //是不是以d结尾的fmt.Println(i1, j1) //false true
获取指定内容在字符串中首次/最后一次出现的位置
str := "hello world"// 获取指定内容在str中首次出现的位置,如果有则返回该元素索引, 如果没有则返回-1fmt.Println(strings.Index(str, "l"), ",", strings.Index(str, "t")) //2 , -1 // 获取指定内容在str中最后一次出现的位置, 如果有则返回该元素索引, 如果没有则返回-1fmt.Println(strings.LastIndex(str, "l"), ",", strings.LastIndex(str, "t")) //9 , -1
替换字符串中指定内容
//将str中的 hello 替换为 你好str := "hello world"fmt.Println(strings.Replace(str, "hello", "你好", 1)) //你好 world //最后一个参数表示如果str中有多个hello的话,只替换前n个
指定内容在字符串中的出现次数
str := "hello world"//字符串中包含某字符串的次数, 没有时返回0fmt.Println(strings.Count(str, "l"), strings.Count(str, "t")) //3 0
字符串整体重复n次
str := "hello world"//将字符串str整体重复n次fmt.Println(strings.Repeat(str, 2))// hello worldhello world
转大小写
//转大写&小写str1 := "HELLO world"fmt.Println(strings.ToLower(str1))//全体转小写 hello worldfmt.Println(strings.ToUpper(str1))//全体转大写 HELLO WORLD
用指定字符将 slice 中所有元素链接成一个字符串
//用指定字符将 string 类型的 slice 中所有元素链接成一个字符串str4 := []string{"a","b","c","d"}fmt.Println(strings.Join(str4,"-"))//用-连接str4中的所有元素a-b-c-d
去除字符串中指定内容(包含空格)
str2 := " hello world tt" //去掉字符串尾指定的字符fmt.Println(strings.TrimRight(str2,"t"))// hello world 字符串首时为TrimLeft() //去掉字符串首尾的空格fmt.Println(strings.TrimSpace(str2))//hello world //去掉字符串首尾指定的字符fmt.Println(strings.Trim(str2,"t"))// hello worldfmt.Println(strings.Trim(str2,"ttt"))//注意相同的字母即时数量比str的多也能去掉 hello worldfmt.Println(strings.Trim(str2," "))//去除首尾空格hello world ttfmt.Println(strings.Trim(str2,"b"))//没有b时不报错返回原字符串 hello world tt
更多相关知识请关注go语言教程栏目
以上就是go语言中一些字符串操作介绍的详细内容,更多请关注24课堂在线网其它相关文章!