5.6 Go 常用函数

最正确的学习模块姿势:

https://golang.org/pkg/        //golang官网

程序开发常用函数

strings处理字符串相关

统计字符串长度,按字节                   len(str)
字符串遍历,处理中文                    r:=[]rune(str)
字符串转整数                           n, err := strconv.Atoi("12")
整数转字符串                           str = strconv.Itoa(12345)
字符串 转 []byte                   var bytes = []byte("hello go")
[]byte 转 字符串                   str = string([]byte{97, 98, 99})
10 进制转 2, 8, 16 进制:              str = strconv.FormatInt(123, 2) // 2-> 8 , 16
查找子串是否在指定的字符串中             strings.Contains("seafood", "foo") //true
统计一个字符串有几个指定的子串         strings.Count("ceheese", "e") //4
不区分大小写的字符串比较(==是区分字母大小写的)  fmt.Println(strings.EqualFold("abc", "Abc")) // true
返回子串在字符串第一次出现的 index 值,如果没有返回-1      strings.Index("NLT_abc", "abc") // 4
返回子串在字符串最后一次出现的 index,如没有返回-1         strings.LastIndex("go golang", "go")
将指定的子串替换成 另外一个子串 strings.Replace("go go hello", "go", "go 语言", n) ,n 可以指 定你希望替换几个,如果 n=-1 表示全部替换
按照指定的某个字符,为分割标识,将一个字符串拆分成字符串数组  strings.Split("hello,wrold,ok", ",")
将字符串的字母进行大小写的转换: strings.ToLower("Go") // go strings.ToUpper("Go") // GO
将字符串左右两边的空格去掉: strings.TrimSpace(" tn a lone gopher ntrn ")
将字符串左右两边指定的字符去掉 : strings.Trim("! hello! ", " !") 
将字符串左边指定的字符去掉 : strings.TrimLeft("! hello! ", " !")
将字符串右边指定的字符去掉 :strings.TrimRight("! hello! ", " !")
判断字符串是否以指定的字符串开头: strings.HasPrefix("ftp://192.168.10.1", "ftp") 
判断字符串是否以指定的字符串结束: strings.HasSuffix("NLT_abc.jpg", "abc") //false

1.1. 时间日期函数

日期时间相关函数经常用到

package time
//time包提供了时间的显示和测量用的函数,日历计算用的是公历

time包用法

package main

import (
    "fmt"
    "time"
)

func main() {
    //获取当前时间
    now := time.Now()
    fmt.Printf("现在时间:%v\n", now)
    fmt.Printf("现在时间类型%T\n", now)
    //通过now获取年月日 时分秒
    fmt.Printf("现在时间 年=%v 月=%v 日=%v 时=%v 分=%v 秒=%v\n", now.Year(), int(now.Month()), now.Day(), now.Hour(), now.Minute(), now.Second())

    //时间格式化,这个时间固定2006-01-02 15:04:05 必须这么写
    fmt.Printf(now.Format("2006-01-02 15:04:05\n"))

    //Unix时间戳和UnixNano用法
    fmt.Printf("unix时间戳=%v unixnano时间戳=%v\n", now.Unix(), now.UnixNano())
}

计算程序执行时间

package main

import (
    "fmt"
    "strconv"
    "time"
)

//计算程序运行时间
func test() {
    str := ""
    for i := 0; i < 100000; i++ {
        //将int转为string
        str += "oldboy" + strconv.Itoa(i)
    }
}

func main() {
    //程序开始前的时间戳
    start := time.Now().Unix()
    test()
    //程序结束时的时间戳
    end := time.Now().Unix()
    fmt.Printf("执行test()函数,花费时间%v秒\n", end-start)
}