Golang03-go语言内置包

string

Golang是利用内置包的形式封装了字符串的方法

package main

import "fmt"

func main()  {
	str:="Hello,Golong"
	//for...range遍历字符串
	for i,ch:=range str{
		fmt.Printf("%d,%c\n",i,ch)
	}
	//遍历所有字节,
	len:=0
	fmt.Printf("----------")
	for i,ch:=range[]byte(str){
		fmt.Printf("%d:%x\n",i,ch)
		len++
	}
	fmt.Printf("字节长度:%d\n",len)	//返回12
	//遍历所有的字符
	count:=0
	for i,ch:=range[]rune(str){
		fmt.Printf("%d:%c",i,ch)
		count++
	}
	fmt.Printf("字符长度:%d\n",count)	//返回12
}


复制代码

1.1字符串处理函数

sample案例字符串相关的函数

package main

import (
	"fmt"
	"strings"
	"unicode"
)

func testContain()  {
	//判断是否包含子串
	fmt.Println(strings.Contains("string","ing"))		//true
	fmt.Println(strings.Contains("seafood","foods"))	//false
}

func testIndex()  {
	//返回字符串中另一个子串出现的位置
	fmt.Println(strings.Index("string","ing"))	//3
	fmt.Println(strings.Index("string","ggg"))	//-1
}
func testCount()  {
	//返回子串在母串的个数
	fmt.Println(strings.Count("cheer","e"))		//2
	fmt.Println(strings.Count("string","e"))		//0
}
func testIndexFunc()  {
	//返回字符串中满足函数f(r)==true字符首次出现的位置
	f:= func(c rune) bool{
		return unicode.Is(unicode.Han,c)
	}
	fmt.Println(strings.IndexFunc("Hello,中国",f))		//6
}

func testLastIndex()  {
	//返回字符串最后一次出现的位置
	fmt.Println(strings.LastIndex("this is a string","i"))	//13
	fmt.Println(strings.LastIndex("this is a string","z"))	//-1
	
}

func main()  {
	testContain()
	testIndex()
	testCount()
	testIndexFunc()
	testLastIndex()
}

复制代码

1.2字符串常用的分割方法

sample字符串分割

package main

import (
	"fmt"
	"strings"
	"unicode"
)

func testFiles()  {
	//将字符串进行分割,返回一个切片
	fmt.Println(strings.Fields("abc 123 ABC xyz XYZ"))  //返回切片[abc 123 ABC xyz XYZ]
}

func testFilesFunc()  {
	f:= func(c rune)bool {
		//return c== '-'
		return !unicode.IsLetter(c)&&!unicode.IsNumber(c)
	}
	fmt.Println(strings.FieldsFunc("abc@123*ABC&xyz%XYZ",f))  //返回切片[abc 123 ABC xyz XYZ]
}

func testSplitAfterN()  {
	fmt.Printf("%q\n",strings.SplitAfterN("a,b,c",",",2)) //返回["a," "b,c"] 
}
func testSplit()  {
	fmt.Printf("%q\n",strings.Split("a,b,c",","))  //返回["a" "b" "c"]
	fmt.Printf("%q\n",strings.Split("a man a plan a canal panama","a "))  //返回["" "man " "plan " "canal panama"]
	fmt.Printf("%q\n",strings.Split("xyz ",""))  //返回["x" "y" "z" " "]
	fmt.Printf("%q\n",strings.Split("","this is a string"))  //[""]
}
func main()  {
	testFiles()
	testFilesFunc()
	testSplitAfterN()
	testSplit()
}

复制代码

1.3字符串大小写转换的方式

1.4常用的修剪字符串

1.5常用的比较字符串

Parse类函数

Parse主要是将字符串转换为其它类型

Format类函数

Format类函数主要的功能是将其它类型格式化成字符串,常用的Format类函数如下表所示

regxp正则表达式包

time包

图片[1]-Golang03-go语言内置包-一一网

math包

随机数rand包

键盘输入

Scanln()函数

键盘输入函数

package main

import "fmt"

func main()  {
	username:=""
	age:=0
	fmt.Scanln(&username,&age)
	fmt.Println("账号信息为:",username,age)
}

复制代码

键盘输入案例,猜数字游戏




复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享