go语言 字符和字符串

一.字符类型    

     var ch byte // 声明字符类型
    ch = 97
    // 格式化输出,%c以字符型输出,%d以整型输出
    fmt.Printf("ch = %c, ch = %d\n", ch, ch)

    ch = 'a' // 字符以单引号
    fmt.Printf("ch = %c, ch = %d\n", ch, ch)

    // 字符大写转小写,小写转大写,大小写相差32,小写大
    fmt.Printf("大写: %d, 小写: %d\n", 'A', 'a')
    fmt.Printf("大写转小写: %c\n", 'A'+32)
    fmt.Printf("小写转大写: %c\n", 'a'-32)

    // 以'\'开头的代表控制字符,不在控制台打印出来
    fmt.Printf("hello go %c", '\n')

    fmt.Printf("hello go ")

    

二.字符串类型   

    var str1 string
    str1 = "acv"
    fmt.Printf("str1 = %s\n", str1)

    // 自动推导类型
    str2 := "hello go world"
    fmt.Printf("str2 = %s\n", str2)
    fmt.Printf("str2 类型是 %T\n", str2)

    // 内建函数,len()可以测定字符串的长度,有多少个字符

    fmt.Printf("len(str2)的长度 %d", len(str2))

     

三.字符和字符串的区别

    var ch byte
    var str string

    // 字符 1.单引号 2.往往只有一个字符,转义字符除外'\n'
    ch = 'a'
    fmt.Printf("ch = %d\n", ch)

     // 字符串 1.双引号 2.字符串由一个或者多个字符组成 3.字符串都是隐藏了一个结束符'\o'
     str = "a" // 由于'a'和'\o'组成

     str = "hello go"

      fmt.Printf("str[0] = %c, str[1] = %c\n", str[0], str[1])

       

猜你喜欢

转载自blog.csdn.net/m0_38068812/article/details/80903699