Go --- 字符串、时间、日期函数

字符串中常用的系统函数

1) 统计字符串的长度, 按字节 len(str)
2) 字符串遍历,同时处理有中文的问题  r:= [ ]rune(str)
3) 字符串转整数:   n, err := strconv.Atoi["12")
4) 整数转字符串  str = srconv.ltoa(12345)
5) 字符串转[ ]byte:  var bytes = [ ]byte("hello go")
6) [ ]byte 转字符串: str= string([ ]byte{97, 98, 99})
7) 10进制转 2, 8, 16进制: str = strconv.FormatInt(123, 2)//2-> 8, 16.
8)  查找子串是否在指定的字符串中: string.Contains("seafood", "food") //true
9)  统计一个字符串有几个指定的子串: strings.Count("ceheese", "e") //4
10) 不区分大小写的字符串比较(==是区分字母大小写的):  fmt.Println(strings.EqualFold("abc", "Abc"))// true
11) 返回子串在字符串第-次出现的index值, 如果没有返回-1 : strings.Index("NLT_ abc", "abc")//4

12) 返回子串在字符串最后一 次出现的index, 如没有返回-1 : strings.LastIndex("go golang", "go")
13) 将指定的子串替换成另外一个子串: strings.Replace("go go hello", "go", "go语言",n) n可以指定你希望替换几个,如果 n= -1表示全部替换
14) 按照指定的某个字符,为分割标识,将一个字符串拆分成字符串数组:string.Split("hello, wrold, ok", ",")
15) 将字符串的字母进行大小写的转换:  strings.ToLower("Go")// go strings.ToUpper("Go") // GO
16)将字符串左右两边的空格去掉:  strngs.TrimSpace(" tn a lone gopher ntrm ")
17) 将字符串左右两边指定的字符去掉:  strings.Trim('"! hello!"," !") // ["hello"] //将左右两
边 ! 和“ “去掉

18) 将字符串左边指定的字符去掉: strings.TrimLeft("! hello!", " !") // [hello"] //将左边!和"
“去掉

19)将字符串右边指定的字符去掉: strings.TrimRight("! hello!"," !") // ["hello"] //将右边!和
“"去掉

20)判断字符串是否以指定的字符串开头: strings.HasPreflx("ftp://192.168.10.1", "ftp" )//true
21)判断字符串是否以指定的字符串结束: strings.HasSuffix("NLT_ abc.jpg", "abs") //false

时间和日期相关函数

1) time.Time 类型,用于表示时间
2) 获取到当前时间的方法:
   now := time.Now() // now的类型就是time.Time

     //获取当前时间

    now := time.Now()

    fmt.Printf("now = %v , now type = %T",now,now)

3) 如何获取到其它的日期信息

//通过now可以获取到年月日,时分秒

    fmt.Printf("年=%v \n",now.Year())

    fmt.Printf("月=%v \n",int(now.Month()))

    fmt.Printf("日=%v \n",now.Day())

    fmt.Printf("时=%v \n",now.Hour())

    fmt.Printf("分=%v \n",now.Minute())

    fmt.Printf("秒=%v \n",now.Second())

4) 格式化日期时间

第一种格式化方式

     fmt.Printf("当前时间 %d-%d-%d  %d:%d:%d \n",now.Year(),

     now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())

     dateStr := fmt.Sprintf("当前时间 %d-%d-%d  %d:%d:%d \n",now.Year(),

     now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())

     fmt.Printf("dataStr=%v \n ",dateStr)

第二种格式化方式

    fmt.Printf(now.Format("2006/01/02 15:04:05"))

     fmt.Println()

     fmt.Printf(now.Format("2006/01/02"))

     fmt.Println()

     fmt.Printf(now.Format("15:04:05"))

     fmt.Println()

“2006/01/02 15:04:05" 这个字符串的各个数字是固定的,必须是这样写
“2006/01/02 15:04:05" 这个字符串各个数字可以自由的组合,这样可以按程序需求来返
回时间和日期

5)时间的常量

const (
    Nanosecond  Duration = 1
    Microsecond          = 1000 * Nanosecond
    Millisecond          = 1000 * Microsecond
    Second               = 1000 * Millisecond
    Minute               = 60 * Second
    Hour                 = 60 * Minute
)

常量的作用: 在程序中可用于获取指定时间单位的时间

 //每隔0.1秒中打印一个数字,打印到50就退出

     i := 0

     for {

        i++

        fmt.Println(i)

        //休眠

        time.Sleep(time.Millisecond * 100)

        if i == 50{

            break

        }

     }

内置函数
Golang设计者为了编程方便,提供了一些函数,这些函数可以直接使用,我们称为Go的内置函数。
1) len:  用来求长度,比如string、 array、 slice. map、 channel
2)new: 用来分配内存,主要用来分配值类型,比如int. float32,struct. .返回的是指针

num1 := 100

    //num1的类型int,num1的值=100,num1的地址0xc0000aa058

    fmt.Printf("num1的类型%T,num1的值=%v,num1的地址%v \n",num1,num1,&num1)

    num2 := new(int)

    //num2的类型 :*int

    //num2的值  :0xc0000aa090 (系统分配地址)----》 0

    //num2的地址 :0xc0000ce020 (系统分配地址)------》 0xc0000aa090

    //num2指向的值: 0

    fmt.Printf("num2的类型%T,num2的值=%v,num2的地址%v,num2指向的值%v \n",num2,num2,&num2,*num2)

3) make: 用来分配内存,主要用来分配引用类型,比如chan、map、slice.。

错误处理

1) Go语言追求简洁优雅,所以,Go语言不支持传统的try..catch..finally这种处理。
2) Go中 引入的处理方式为: defer, panic, recover
3) 这几个异常的使用场景可以这么简单描述: Go中可以抛出一个panic的异常,然.
后在defer中通过recover捕获这个异常,然后正常处理.

使用defer+recover来处理错误

   test()

   fmt.Println("...dsfdfd......")

func test(){

    //使用defer+recover来处理错误

    defer func() {

        err := recover() //recover()内置函数,可以捕获异常

        if err != nil{

            fmt.Println("err=",err)

        }

    }()

    num1 := 1

    num2 := 0

    res := num1/num2

    fmt.Println("res=",res)

}

自定义错误
Go程序中,也支持自定义错误,使用errors.New 和 panic 内置函数。
1) errors.New(" 错误说明") ,会返回一个error类型的值,表示一个错误
2) panic内置 函数,按收一个interface{}类型的值(也就是任何值了)作为参数。可以接收error
类型的变量,输出错误信息,并退出程序.

func test2(){

    err := readConf("config")

    if err != nil {

      //如果读取文件发送错误,就输出这个错误,并终止程序

        panic(err)

    }

    fmt.Println("test2......")

}

//函数去读取以配置文件init. conf的信息

//如果文件名传入不正确,我们就返回一个自定义的错误

func readConf(name string )(err error){

    if name == "config.ini"{

        //读取代码

        return nil

    }else{

         return errors.New(" read file error!!!")

    }

}

   test2()

   fmt.Println("...dsfdfd......")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值