- A+
所属分类:编程茶楼
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
//1
str := "hello杯" //goland统一为utf-8(字母数字占一个字节,汉字占3个字节)
fmt.Println(len(str))
//len是按字节返回的,不是按字符
//2
str2 := "hello被禁"
r := []rune(str2)
for i := 0; i < len(r); i++ { //处理有中文,转切片
fmt.Printf("str2:%c", r[i])
}
//3 string转int
n, err := strconv.Atoi("123")
if err != nil {
fmt.Printf("转换错误")
} else {
fmt.Println("结果:", n)
}
//4 int转string
str = strconv.Itoa(123)
fmt.Printf("%v,%T", str, str)
//5 string转byte
var bytes = []byte("hello,go") //转字节
fmt.Printf("%v\n", bytes)
//6 byte转string
str = string([]byte{97, 98, 99})
fmt.Printf("%v\n%T", str, str)
//7
str = strconv.FormatInt(123, 2) //int转2进制
fmt.Println(str)
str = strconv.FormatInt(123, 16) //int转16进制
fmt.Printf(str)
//8 匹配
b := strings.Contains("setfoot", "foot")
fmt.Printf("%v", b) //true
//9 统计字符传个数
num := strings.Count("ceheess", "e") //3
fmt.Printf("%v", num)
//10 不区分大小写判断
b = strings.EqualFold("abc", "ABC") //true
fmt.Printf("%v", b) //不区分大小写
//区分大小写判断
fmt.Println("abc" == "ABC") //区分大小写
//11 //找到第一次下标
index := strings.Index("abcdefadef", "def")
fmt.Printf("%v\n", index)
//12判断字符串最后一次出现的位置
index = strings.LastIndex("abcgewfecgs", "cg")
fmt.Printf("%v\n", index)
//13替换字符串,-1为全部替换,值传递
str = strings.Replace("go go hello", "go", "java", -1)
fmt.Printf("%v\n", str)
//14按要求分割数组,值拷贝
strArr := strings.Split("hello,ok,world", ",")
fmt.Printf("%v\n", strArr)
for i := 0; i < len(strArr); i++ {
fmt.Printf("str[%v]=%v\n", i, strArr[i])
}
//15大小写转换
str = "goLand Hello"
str = strings.ToLower(str) //全部转小写
str = strings.ToUpper(str) //全部转大写
fmt.Printf("%v\n", str)
//16去掉左右空格
str = strings.TrimSpace(" tn f fssd fs ")
fmt.Printf("%q\n", str)
//17指定去左右字符
str = strings.Trim("! he!llo! ", " ")
str = strings.TrimLeft(" ! he!llo! ", " ")
str = strings.TrimRight(" ! he!llo! ", " ")
fmt.Printf("%q\n", str)
//20判断字符串是否指定开头:
b = strings.HasPrefix("ftp://1542.434.232.423", "ftp")
fmt.Printf("%v\n", b)
b = strings.HasSuffix("ftp://1542.434.232.423", "ftp")
fmt.Printf("%v\n", b)
}
- 我的微信
- 这是我的微信扫一扫
- 我的微信公众号
- 我的微信公众号扫一扫