0
点赞
收藏
分享

微信扫一扫

go 语言学习笔记(15)——字符串常用函数

GhostInMatrix 2022-02-06 阅读 86

文章目录

go 语言学习笔记(15)——字符串常用函数

字字符串操作

Contains

func Contains(s , substr string) bool
功能:字符串s中是否包含subsrt 返回bool类型

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Contains("hxw", "xw"))
	fmt.Println(strings.Contains("hxw", "xc"))
}
/*
true
false
*/

Join

func Join(a [] string , sep string) string
功能:字符串连接,把切片a 通过sep连接起来

package main

import (
	"fmt"
	"strings"
)

func main() {
	all := []string{"abc", "hello", "hxw"}
	fmt.Println(strings.Join(all, "+"))
}
//abc+hello+hxw

Index

func Index(s , sep string)int
功能:在字符串s中查找sep的位置,返回位置值, 没有返回-1

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Index("hxw", "x"))
	fmt.Println(strings.Index("hxw", "xc"))
}
/*
1
-1
*/

Repeat

func Repeat(s string , count int) string
功能:重复s字符串count次, 最后返回重复的字符串

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Repeat("ab", 2))

}
//abab

Replace

func Replace(s, old , new string , n int) string
功能:在s字符串中, 把old字符串替换成new字符串,n代表替换次数, 小于0表示全部替换

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Replace("hxwhxwhxwhxw", "x", "aa", 2))
	fmt.Println(strings.Replace("hxwhxwhxwhxw", "x", "aa", -1))

}
/*
haawhaawhxwhxw
haawhaawhaawhaaw
*/

Split

func Split(s , sep string)[]string
功能:把s字符串按照sep分割, 返回slice

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Split("hxwhxwhxwhxw", "x"))

}
//[h wh wh wh w]

Trim

func Trim(s string , cutset string) string
功能:在s字符串的头部和尾部去除cutset指定的字符串

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Trim("     hxwhxwhxwhxw    ", " "))

}
//hxwhxwhxwhxw

Fields

func Fields(s string )[]string
功能:去除s字符串中的空格符, 并且按照空格分割返回slice

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Fields("     hxwh xwh xwh xw    "))

}
//[hxwh xwh xwh xw]

字符串转换

Appen

将整数等转化为字符串, 添加到现有的字节数组中

package main

import (
	"fmt"
	"strconv"
)

func main() {
	sli := make([]byte, 0, 1024)
	sli = strconv.AppendBool(sli, true)
	fmt.Println(string(sli))
	sli = strconv.AppendInt(sli, 2, 10)
	fmt.Println(string(sli))
	sli = strconv.AppendQuote(sli, "hxw")
	fmt.Println(string(sli))

}
/*
true
true2
true2"hxw"
*/

Format

把其他类型转化为字符串

package main

import (
	"fmt"
	"strconv"
)

func main() {
	fmt.Println(strconv.FormatBool(false))
	fmt.Println(strconv.FormatFloat(3.14, 'f', -1, 64))
	//f打印格式, -1小数点侯几位,64以float64处理
	fmt.Println(strconv.FormatFloat(3.14, 'f', 1, 64))
	fmt.Println(strconv.Itoa(666))
}
/*
false
3.14
3.1
666
*/
举报

相关推荐

0 条评论