总结
豆包 AI 助手文章总结
首页 > 后端开发 > Golang > 正文

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

WBOY
发布: 2024-08-12 12:57:04
转载
880人浏览过

介绍

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

在上一课中,我们了解到 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 := "shiyanlou\nlabex"
    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: %d\n", a, len(a))
    fmt.printf("the value of b is %s, the byte length of b is: %d\n", b, len(b))
    fmt.printf("the value of c is %s, the byte length of c is: %d\n", c, len(c))

    // output string length
    fmt.printf("the length of d is: %d\n", 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: %t\n", a)   // string
    fmt.printf("the type of b: %t\n", b)   // int
    fmt.printf("the type of c: %t\n", c)   // int
    fmt.printf("the type of d1: %t\n", d1) // string
    fmt.printf("the type of d2: %t\n", 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

以上就是去编程 |字符串基础知识 |字符编码的详细内容,更多请关注php中文网其它相关文章!

豆包AI编程
豆包AI编程

智能代码生成与优化,高效提升开发速度与质量!

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号