Go-字符串中常用的函数

package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    var str string = "你好,世界"

    // 统计字符串长度
    strLen := len(str)
    fmt.Println(strLen) // 15

    // 字符串遍历
    runeStr := []rune(str)
    for index,value := range runeStr {
        fmt.Printf("index=%d,value=%c ", index, value)
    }
    // index=0,value=你 index=1,value=好 index=2,value=, index=3,value=世 index=4,value=界

    // 字符串转整数
    n,_ := strconv.Atoi("12")
    fmt.Println(n) // 12

    // 整数转字符串
    n1 := strconv.Itoa(12)
    fmt.Println(n1) // 12

    // 字符串转 []byte
    s1 := []byte(str)
    fmt.Println(s1) // [228 189 160 229 165 189 239 188 140 228 184 150 231 149 140]

    // []byte 转字符串
    s2 := string(s1)
    fmt.Println(s2) // 你好,世界

    // 十进制转二进制
    s3 := strconv.FormatInt(123, 2)
    fmt.Println(s3) // 1111011

    // 查找子串是否在指定的字符串中
    s4 := strings.Contains("hello word", "llo")
    fmt.Println(s4) // true

    // 统计一个字符串有几个指定的子串
    s5 := strings.Count("ceheese", "e")
    fmt.Println(s5) // 4

    // 不区分大小写的字符串比较
    s6 := strings.EqualFold("abc", "Abc")
    fmt.Println(s6) // true

    // 返回子串在字符串第一次出现的index值,如果没有返回-1
    s7 := strings.Index("asdfasdfasdf", "d")
    fmt.Println(s7) // 2

    // 返回子串在字符串最后一次出现的index,如果没有返回-1
    s8 := strings.LastIndex("asdfasdfasdf", "f")
    fmt.Println(s8) // 11

    // 将指定的子串替换成另外一个子串
    s9 := strings.Replace("hello world", "world", "bndong", -1)
    fmt.Println(s9) // hello bndong

    // 按照指定的某个字符为分割标识,将一个字符串拆分成字符串数组
    s10 := strings.Split("a,b,c,d,e", ",")
    fmt.Println(s10) // [a b c d e]

    // 按照指定的某个字符为拼接标识,将一个字符串数组拼接成字符串
    e1 := strings.Join(s10, "_")
    fmt.Println(e1) // a_b_c_d_e

    // 重复字符串
    e2 := strings.Repeat("aaa ", 3)
    fmt.Println(e2) // aaa aaa aaa

    // 将字符串的字母进行大小写转换
    s11 := strings.ToLower("BNDong")
    s12 := strings.ToUpper("BNDong")
    fmt.Println(s11) // bndong
    fmt.Println(s12) // BNDONG

    // 将字符串的左右两边的空格去掉
    s13 := strings.TrimSpace(" 123123 ")
    fmt.Println(s13) // 123123

    // 将字符串左右两边指定的字符去掉
    s14 := strings.Trim("! 123123 !", "")
    fmt.Println(s14) //  123123

    // 将字符串左边指定的字符去掉
    s15 := strings.TrimLeft("! 123123 !", "")
    fmt.Println(s15) //  123123 !

    // 将字符串右边指定的字符去掉
    s16 := strings.TrimRight("! 123123 !", "")
    fmt.Println(s16) // ! 123123

    // 判断字符串是否以指定的字符串开头
    s17 := strings.HasPrefix("http://127.0.0.1", "http")
    fmt.Println(s17) // true

    // 判断字符串是否以指定的字符串结束
    s18 := strings.HasSuffix("http://127.0.0.1", "0.1")
    fmt.Println(s18) // true
}

 

posted @ 2019-07-31 10:16  GJH-  阅读(53)  评论(0)    收藏  举报