今天我們繼續說一下,在go 語言中,字符串是的一些相關操作。
我們在對字符串進行處理時,需要藉助包:“strings",下面我們說一下常用的字符串處理函數
一、Contains函數
查找字符串中是否包含某些值,返回bool結果。
package main
import (
"fmt"
"strings"
)
func main() {
str:="helloworld"
value:=strings.Contains(str,"hell")
fmt.Println(value)
if value{
fmt.Println("找到")
}else {
fmt.Println("未找到")
}
}
結果:
true
找到
可以看到,Contains(str1,str2),在str1中,查找,str2是否在str1中出現,模糊查找,切查找是連續的。
二、Join
字符串的連接,字符串的拼接操作。
Join(a []string, sep string) string ,將一個字符串切片,拼接成一個字符串。
package main
import (
"fmt"
"strings"
)
func main() {
s:=[]string{"1234","5678","2222","3333"}
str:=strings.Join(s,"-")
fmt.Println(str)
}
結果:
1234-5678-2222-3333
三、Index
Index(s, sep string) int
在字符串中,查找sep 所在的位置,返回位置下標,找不到返回-1
package main
import (
"fmt"
"strings"
)
func main() {
str:="123456789"
value:=strings.Index(str,"9")
fmt.Println(value)
}
結果:
8
四、Repeat
Repeat(s string , count int) string
重複s字符串,count 次,返回重複的字符串。
package main
import (
"fmt"
"strings"
)
func main() {
str:="123456789"
value:=strings.Repeat(str,2)
fmt.Println(value)
}
結果:
123456789123456789
五、Replace
Replace(s,old, new string,n int) string
在s字符串中,把old字符串替換爲new 字符串,n表示替換次數,小於0表示全部替換。
package main
import (
"fmt"
"strings"
)
func main() {
str:="helloworld"
value:=strings.Replace(str,"l","w",3 )
fmt.Println(value)
}
結果:將l 替換w,替換3次。可多個替換,替換次數-1表示全部替換
hewwoworwd
六、Split
Split(s,sep string)[]string
把s字符串,按照sep分割,返回slice
package main
import (
"fmt"
"strings"
)
func main() {
str:="www.baidu.com"
value:=strings.Split(str,"." )
fmt.Println(value)
}
結果:
[www baidu com]
七、Trim
Trim(s string, cutest string) string
在s字符串的頭部和尾部去除 cutest 指定的字符串
package main
import (
"fmt"
"strings"
)
func main() {
str:="................www.baidu.com....................."
value:=strings.Trim(str,"." )
fmt.Println(value)
}
結果:
www.baidu.com
八、Fields
Fields(s string)[]string
去除s字符串的空格符,並且按照空格分割返回slice
package main
import (
"fmt"
"strings"
)
func main() {
str:=" Hi hello World "
value:=strings.Fields(str)
fmt.Println(value)
}
結果:
[Hi hello World]