字符串类型

一、定义:

  1、字符串在 GO语言中以原生数据类型出现,使用字符串就像使用其他原生数据类型(int、bool、float32、float64 等)一样。

  2、字符串转译符

    

  

package main
import (
    "fmt"
)
func main() {
    fmt.Println("str := "c:\Go\bin\go.exe"")
}


#str := "c:Goingo.exe"
转译符的使用

  3、字符串实现基于 UTF-8 编码

    Go 语言里的字符串的内部实现使用 UTF-8 编码。通过 rune 类型,可以方便地对每个 UTF-8 字符进行访问。当然,Go 语言也支持按传统的 ASCII 码方式进行逐字符访问。

  4、定义多行字符串

    在源码中,将字符串的值以双引号书写的方式是字符串的常见表达方式,被称为字符串字面量(string literal)。这种双引号字面量不能跨行。如果需要在源码中嵌入一个多行字符串时,就必须使用`字符  

package main
import (
    "fmt"
)
func main() {
    const str = ` 第一行
                        第二行
                        第三行
                        

                      `
fmt.Println(str)
}


#第一行
#第二行
#第三行
#
定义多行字符串

    `叫反引号,就是键盘上 1 键左边的键,两个反引号间的字符串将被原样赋值到 str 变量中。

    在这种方式下,反引号间换行将被作为字符串中的换行,但是所有的转义字符均无效,文本将会原样输出。

const codeTemplate = `// Generated by github.com/davyxu/cellnet/
protoc-gen-msg
// DO NOT EDIT!{{range .Protos}}
// Source: {{.Name}}{{end}}
package {{.PackageName}}
{{if gt .TotalMessages 0}}
import (
    "github.com/davyxu/cellnet"
    "reflect"
    _ "github.com/davyxu/cellnet/codec/pb"
)
{{end}}
func init() {
    {{range .Protos}}
    // {{.Name}}{{range .Messages}}
    cellnet.RegisterMessageMeta("pb","{{.FullName}}", reflect.TypeOf((*{{.Name}})(nil)).Elem(), {{.MsgID}})    {{end}}
    {{end}}
}
`

#这段代码只定义了一个常量 codeTemplate,类型为字符串,使用`定义。字#符串的内容为一段代码生成中使用到的 Go 源码格式。

#在`间的所有代码均不会被编译器识别,而只是作为字符串的一部分。
定义多行字符串2

二、Go语言计算字符串长度——len()和RuneCountInString()

  1、len()和RunCountlnString()的区别

tip1 := "genji is a ninja"
fmt.Println(len(tip1))
tip2 := "忍者"
fmt.Println(len(tip2))


#16
#6
len()

    len() 函数的返回值的类型为 int,表示字符串的 ASCII 字符个数或字节长度。

      · 输出中第一行的 16 表示 tip1 的字符个数为 16。

      · 输出中第二行的 6 表示 tip2 的字符格式,也就是“忍者”的字符个数是 6,然而根据习惯,“忍者”的字符个数应该是 2。

    这里的差异是由于 Go 语言的字符串都以 UTF-8 格式保存,每个中文占用 3 个字节,因此使用 len() 获得两个中文文字对应的 6 个字节。

    如果希望按习惯上的字符个数来计算,就需要使用 Go 语言中 UTF-8 包提供的 RuneCountInString() 函数,统计 Uncode 字符数量。

fmt.Println(utf8.RuneCountInString("忍者"))
fmt.Println(utf8.RuneCountInString("龙忍出鞘,fight!"))



#2
#11
RuneCountInString()

  总结:

    1. ASCII 字符串长度使用 len() 函数。

    2. Unicode 字符串长度使用 utf8.RuneCountInString() 函数。

三、Go语言遍历字符串——获取每一个字符串元素

  1、遍历每一个ASCII字符

theme := "狙击 start"
for i := 0; i < len(theme); i++ {
    fmt.Printf("ascii: %c  %d
", theme[i], theme[i])
}




#ascii: ?  231
#ascii:     139
#ascii:     153
#ascii: ?  229
#ascii:     135
#ascii: ?  187
#ascii:    32
#ascii: s  115
#ascii: t  116
#ascii: a  97
#ascii: r  114
#ascii: t  116
遍历每一个ASCII字符

  2、按Unicode字符遍历字符串

theme := "狙击 start"
for _, s := range theme {
    fmt.Printf("Unicode: %c  %d
", s, s)
}


#Unicode: 狙  29401
#Unicode: 击  20987
#Unicode:    32
#Unicode: s  115
#Unicode: t  116
#Unicode: a  97
#Unicode: r  114
#Unicode: t  116
按Unicode字符遍历字符串

  3、总结

    1.ASCII字符串遍历直接使用下标。

    2.Unicode字符串遍历用for range。

 

原文地址:https://www.cnblogs.com/ppzhang/p/10930477.html