golang-101-hacks(10)——String

栏目: Go · 发布时间: 6年前

内容简介:注:本文是对在Go中string是由不可变的字节数组构成的。一旦赋值,就不能修改字符串的值。例如In

注:本文是对 golang-101-hacks 中文翻译。

Go 中string是由不可变的字节数组构成的。一旦赋值,就不能修改字符串的值。例如

In Go , string is an immutable array of bytes. So if created, we can't change its value. E.g.:

package main

func main()  {
    s := "Hello"
    s[0] = 'h'
}

编译结果会提示错误:

The compiler will complain:

cannot assign to s[0]

对字符串的修改可以将其转换为“byte”数组。但是实际上您并没有对原始字符串进行修改操作,改变的只是一个原始字符串的副本。

To modify the content of a string, you could convert it to a byte array. But in fact, you do not operate on the original string, just a copy:

package main

import "fmt"

func main()  {
    s := "Hello"
    b := []byte(s)
    b[0] = 'h'
    fmt.Printf("%s\n", b)
}

运行结果

The result is like this:

hello

Go使用的是UTF-8的编码方式,函数len的结果是当前字符字节的长度而不是字符长度

Since Go uses UTF-8 encoding, you must remember the len function will return the string's byte number, not character number:

package main

import "fmt"

func main()  {
    s := "日志log"
    fmt.Println(len(s))
}

执行结果是

The result is:

由于每个中文占3个字节,上面的例子中s字符串有5个字符和9个字节组成的

Because each Chinese character occupied 3 bytes, s in the above example contains 5 characters and 9 bytes.

对字符串执行 for ... range 循环语句可以获取到每个字符

If you want to access every character, for ... range loop can give a help:

package main
import "fmt"

func main() {
    s := "日志log"
    for index, runeValue := range s {
        fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
    }
}

执行结果

U+65E5 '日' starts at byte position 0
U+5FD7 '志' starts at byte position 3
U+006C 'l' starts at byte position 6
U+006F 'o' starts at byte position 7
U+0067 'g' starts at byte position 8

参考

Strings, bytes, runes and characters in Go ;

The Go Programming Language .


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

司法的过程

司法的过程

(美)亨利·J.亚伯拉罕 / 泮伟江 宦盛奎 韩阳 / 北京大学出版社 / 2009-07-28 / 58.00元

本书是以比较研究的方法来分析司法哲学的经典文本之一。作者以敏锐的眼光透视了司法过程背后的理论、实践和参与其中的人。比较了美国、英国、法国的具体法院运作,审视了“司法能动主义”和“司法克制主义”之间的争辩。本书第七版的介绍吸收了美国、英国、法国和欧洲法院体系运作中的最新和重要的发展。 目前国内非常关注司法的运作过程、法官的裁判过程,此书的翻译对于这方面的研究很有助益,对于英国和法国法院的介绍填补了国......一起来看看 《司法的过程》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换