本文总结了 go 语言中对字符串的常见操作示例,这些示例都是在日常开发中经常会遇到的 go 语言字符串操作,也可以更好的理解 go 语言的 strings 包。
Go语言获取字符串长度
package main
import (
"fmt"
)
func main() {
s := "Hello,www.02405.com!"
l := len(s)
fmt.Println(l)
}
输出:20
Go语言拆分字符串
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello! our site's url is https://www.02405.com"
a := strings.Split(s, " ")
for _, value := range a {
fmt.Println(value)
}
}
输出:
Hello!
our
site's
url
is
https://www.02405.com
Go语言使用正则表达式拆分字符串
package main
import (
"fmt"
"regexp"
)
func main() {
s := "Hello! our site's url is https://www.02405.com"
r := regexp.MustCompile("[0-9]+")
st := r.Split(s, -1)
fmt.Print(st[1])
}
输出:.com
Go语言检查字符串中是否包含指定字符串
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello! our site's url is https://www.02405.com"
t := strings.Contains(s, "02405")
f := strings.Contains(s, "零五网")
fmt.Println(t, f)
}
输出:true false
Go语言获取字符串中指定字符(串)的索引位置
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello! our site's url is https://www.02405.com"
i := strings.Index(s, "02405")
fmt.Println(i)
}
输出:37
Go语言将字符串数组连接成字符串
package main
import (
"fmt"
"strings"
)
func main() {
s := []string{"Hello!", "our", "site's", "url", "is", "https://www.02405.com"}
l := strings.Join(s, " ")
fmt.Println(l)
}
输出:Hello! our site's url is https://www.02405.com
Go语言将字符串替换
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello! Our site's url is https://www.02405.com!"
l := strings.Replace(s, "!", ",", 1)
l1 := strings.Replace(s, "!", ",", -1)
fmt.Println(l)
fmt.Println(l1)
}
输出:
Hello, Our site's url is https://www.02405.com! Hello, Our site's url is https://www.02405.com,
Go语言字符串大小写转换
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello! Our site's url is https://www.02405.com."
l := strings.ToLower(s)
u := strings.ToUpper(s)
fmt.Println(l)
fmt.Println(u)
}
输出:
hello! our site's url is https://www.02405.com. HELLO! OUR SITE'S URL IS HTTPS://WWW.02405.COM.