卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章73806本站已运行433

去编程 |字符串基础知识 |字符编码

介绍

去编程 |字符串基础知识 |字符编码

在上一课中,我们了解到 go 中的字符使用 utf-8 进行编码并存储为 byte 或 rune 类型。现在,我们来谈谈字符串,它是字符的集合。一起来了解一下吧

知识点:

  • 什么是字符串
  • 创建字符串
  • 声明一个字符串
  • 常用字符串函数

什么是字符串

在我们用 go 学习的第一个程序中,我们打印了字符串 hello, world。

string 是 go 中的一种基本数据类型,也称为字符串文字。可以理解为字符的集合,占用一块连续的内存块。这块内存可以存储任何类型的数据,比如字母、文本、表情符号等

但是,与其他语言不同,go 中的字符串是只读的,无法修改。

创建字符串

字符串可以通过多种方式声明。我们来看看第一种方法。创建一个名为 string.go 的新文件:

touch ~/project/string.go

编写以下代码:

package main

import "fmt"

func main() {
    // use the var keyword to create a string variable a
    var a string = "labex"
    a = "labex" // assign "labex" to variable a

    // declare variable a and assign its value
    var b string = "shiyanlou"

    // type declaration can be omitted
    var c = "monday"

    // use := for quick declaration and assignment
    d := "hangzhou"
    fmt.println(a, b, c, d)
}

上面的代码演示了如何使用 var 关键字和 := 运算符创建字符串。如果用var创建变量时赋值,可以省略类型声明,如创建变量b所示。

预期输出如下:

labex shiyanlou monday hangzhou

声明一个字符串

大多数情况下,我们使用双引号“”来声明字符串。双引号的优点是可以用作转义序列。例如,在下面的程序中,我们使用 n 转义序列来创建新行:

package main

import "fmt"

func main(){
    x := "shiyanlounlabex"
    fmt.println(x)
}

预期输出如下:

shiyanlou
labex

以下是一些常见的转义序列:

符号 描述
n 新线路
r 回车
t 标签
b 退格键
反斜杠
' 单引号
双引号

如果想保留文本的原始格式或者需要使用多行,可以使用反引号来表示:

package main

import "fmt"

func main() {
    // output pascal's triangle
    yanghuitriangle := `
            1
            1 1
            1 2 1
            1 3 3 1
            1 4 6 4 1
            1 5 10 10 5 1
            1 6 15 20 15 6 1
            1 7 21 35 35 21 7 1
            1 8 28 56 70 56 28 8 1`
    fmt.println(yanghuitriangle)

    // output the ascii art of "labex"
    ascii := `
        #        ##   #    #  ###  #   ##    ####
        #       #  #  ##   # #    # #  #  #  #    #
        #      #    # # #  # #    # # #    # #    #
        #      ##### #  # # #  # # # ##### #    #
        #      #    # #   ## #   #  # #    # #    #
        ##### #    # #    #  ## # # #    #  ###  `
    fmt.println(ascii)
}

运行程序后,您将看到以下输出:

去编程 |字符串基础知识 |字符编码

反引号常用于提示、html 模板以及其他需要保留输出原始格式的情况。

获取字符串的长度

在上一课中,我们了解到英文字符和一般标点符号占用一个字节,而汉字则占用三到四个字节。

因此,在go中,我们可以使用len()函数来获取字符串的字节长度。如果不存在占用多个字节的字符,可以使用len()函数来近似测量字符串的长度。

如果字符串中包含占用多个字节的字符,可以使用 utf8.runecountinstring 函数获取字符串中的实际字符数。

让我们看一个例子。将以下代码写入string.go文件:

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    // declare two empty strings using var and :=
    var a string
    b := ""

    c := "labex"

    // output byte length
    fmt.printf("the value of a is %s, the byte length of a is: %dn", a, len(a))
    fmt.printf("the value of b is %s, the byte length of b is: %dn", b, len(b))
    fmt.printf("the value of c is %s, the byte length of c is: %dn", c, len(c))

    // output string length
    fmt.printf("the length of d is: %dn", utf8.runecountinstring(d))
}

预期输出如下:

the value of a is , the byte length of a is: 0
the value of b is , the byte length of b is: 0
the value of c is labex, the byte length of c is: 5
the length of d is: 9

在程序中,我们首先声明了两个空字符串和字符串labex。可以看到他们的字节长度和实际长度是一样的

转换字符串和整数

我们可以使用 strconv 包中的函数在字符串和整数之间进行转换:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // declare a string a and an integer b
    a, b := "233", 223

    // use atoi to convert an integer to a string
    c, _ := strconv.atoi(a)

    // use sprintf and itoa functions respectively
    // to convert a string to an integer
    d1 := fmt.sprintf("%d", b)
    d2 := strconv.itoa(b)

    fmt.printf("the type of a: %tn", a)   // string
    fmt.printf("the type of b: %tn", b)   // int
    fmt.printf("the type of c: %tn", c)   // int
    fmt.printf("the type of d1: %tn", d1) // string
    fmt.printf("the type of d2: %tn", d2) // string
}

预期输出如下:

the type of a: string
the type of b: int
the type of c: int
the type of d1: string
the type of d2: string

在程序中,我们使用了fmt包中的sprintf()函数,其格式如下:

func sprintf(format string, a ...interface{}) string

format 是带有转义序列的字符串,a 是为转义序列提供值的常量或变量,... 表示可以有多个与 a 类型相同的变量。函数后面的字符串代表sprintf返回一个字符串。这是使用此功能的示例:

a = sprintf("%d+%d=%d", 1, 2, 3)
fmt.println(a) // 1+2=3

在这段代码中,format 传递了三个整型变量 1、2、3。format 中的 %d 整型转义字符被整型值替换,sprintf 函数返回替换后的结果,1+2= 3.

另外,请注意,当使用 strconv.atoi() 将整数转换为字符串时,该函数返回两个值,即转换后的整数 val 和错误代码 err。因为在go中,如果声明了变量,就必须使用它,我们可以使用下划线_来注释掉err变量。

当strconv.atoi()正确转换时,err返回nil。当转换出错时,err返回错误信息,val的值为0。你可以改变字符串a的值,将下划线替换为普通变量来尝试一下。

连接字符串

连接两个或多个字符串的最简单方法是使用 + 符号。我们还可以使用 fmt.sprintf() 函数来连接字符串。让我们看一个例子:

package main

import (
    "fmt"
)

func main() {
    a, b := "lan", "qiao"
    // concatenate using the simplest method, +
    c1 := a + b
    // concatenate using the sprintf function
    c2 := fmt.sprintf("%s%s", a, b)
    fmt.println(a, b, c1, c2) // lan qiao labex labex
}

预期输出如下:

lan qiao labex labex

在程序中,我们还使用了 fmt 包中的 sprintf() 函数来连接字符串并打印结果。

从字符串中删除前导和尾随空格

我们可以使用 strings.trimspace 函数删除字符串中的前导和尾随空格。该函数接受一个字符串作为输入,并返回删除了前导和尾随空格的字符串。格式如下:

func trimspace(s string) string

这是一个例子:

package main

import (
    "fmt"
    "strings"
)

func main() {
    a := " t n  labex n t hangzhou"
    fmt.println(strings.trimspace(a))
}

预期输出如下:

labex
    hangzhou

概括

总结一下我们在本课中学到的内容:

  • 字符串和字符的关系
  • 声明字符串的两种方法
  • 连接字符串
  • 删除字符串中的前导空格和尾随空格

在本课中,我们解释了日常生活中使用的字符串。我们了解了字符串和字符之间的关系,掌握了字符串的创建和声明,并了解了一些常用字符串函数的知识。

在下一课中,我们将学习常量。


? 立即练习:go 弦乐基础知识

想了解更多吗?

  • ? 学习最新的围棋技能树
  • ? 阅读更多 go 教程
  • ? 加入我们的 discord 或发推文@wearelabex
卓越飞翔博客
上一篇: 谁不太适合使用 Golang 框架?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏