golang的字符串操作
Go语言简介
Go(又称Golang)是Google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言。
罗伯特·格瑞史莫(Robert Griesemer),罗勃·派克(Rob Pike)及肯·汤普逊(Ken Thompson)于2007年9月开始设计Go,稍后Ian Lance Taylor、Russ Cox加入项目。Go是基于Inferno操作系统所开发的。Go于2009年11月正式宣布推出,成为开放源代码项目,并在Linux及Mac OS X平台上进行了实现,后来追加了Windows系统下的实现。在2016年,Go被软件评价公司TIOBE 选为“TIOBE 2016 年最佳语言”。 目前,Go每半年发布一个二级版本(即从a.x升级到a.y)。
按单个/多个字符分割字符串
按指定内容切割字符串
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语言中一些字符串操作介绍的详细内容,更多请关注亿速云其它相关文章!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。