go语言怎么修改字符串中的某一个字符?go语言的字符串是UTF-8编码的、不可改变的字节序列 。
要修改字符串,只能以原串为基?。?创建一个新串 。下面的图中是一个参考示例 , 提供了以原串为蓝本,创建新串的两种方法 。
代码
输出
golang获取到string和直接赋值strimg不一样1、 string的定义
Golang中的string的定义在reflect包下的value.go中,定义如下:
StringHeader 是字符串的运行时表示,其中包含了两个字段,分别是指向数据数组的指针和数组的长度 。
// StringHeader is the runtime representation of a string.
// It cannot be used safely or portably and its representation may
// change in a later release.
// Moreover, the Data field is not sufficient to guarantee the data
// it references will not be garbage collected, so programs must keep
// a separate, correctly typed pointer to the underlying data.
type StringHeader struct {
Data uintptr
Lenint
}
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
2、string不可变
Golang中的字符串是不可变的,不能通过索引下标的方式修改字符串中的数据:
在这里插入图片描述
运行代码 , 可以看到编译器报错,string是不可变的
在这里插入图片描述
但是能不能进行一些骚操作来改变元素的值呢?
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
a := "hello,world"
b := a[6:]
bptr := (*reflect.StringHeader) (unsafe.Pointer(b))
fmt.Println(a)
fmt.Println(b)
*(*byte)(unsafe.Pointer(bptr.Data)) = '.'
fmt.Println(a)
fmt.Println(b)
}
// 运行结果
hello,world
world
unexpected fault address 0x49d7e3
fatal error: fault
[signal 0xc0000005 code=0x1 addr=0x49d7e3 pc=0x4779fa]
goroutine 1 [running]:
runtime.throw(0x49c948, 0x5)
C:/Program Files/Go/src/runtime/panic.go:1117 +0x79 fp=0xc0000dbe90 sp=0xc0000dbe60 pc=0x405fd9
runtime.sigpanic()
C:/Program Files/Go/src/runtime/signal_windows.go:245 +0x2d6 fp=0xc0000dbee8 sp=0xc0000dbe90 pc=0x4189f6
main.main()
F:/go_workspace/src/code/string_test/main.go:20 +0x13a fp=0xc0000dbf88 sp=0xc0000dbee8 pc=0x4779fa
runtime.main()
C:/Program Files/Go/src/runtime/proc.go:225 +0x256 fp=0xc0000dbfe0 sp=0xc0000dbf88 pc=0x4087f6
runtime.goexit()
C:/Program Files/Go/src/runtime/asm_amd64.s:1371 +0x1 fp=0xc0000dbfe8 sp=0xc0000dbfe0 pc=0x435da1
Process finished with the exit code 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
在上面的代码中,因为在go语言中不能进行指针的加减运算,因此取切片,让b的Data指针指向’,'所在的位置 。然后把"hello,world"中的逗号改为点,但是发现还是不行,程序直接崩溃了 。看来go语言中的指针得到了大大的限制,设计者并不想让程序员过度使用指针来写出一些不安全的代码 。
- mysql怎么把两个字段拼在一起 mysql字段拼接中文
- mongodb查询字符串字段包含 mongodb查询字段不为空
- mongodb连接字符串 mongodb映射字段
- mongodb 替换字符串 mongodb切割字符串
- mysql 查找字符位置 mysql查找字符串最后
- 将数据保存到文件中c语言 将数据保存到mongodb
- mongodb查询字符串字段包含 mongodb字段类型为数组查询
- 罗布人村天气 mysql语言具有的功能
- redis编程语言 redis对应c语言
- 有没有中文版的英菲尼迪电路图 有没有中文版的mongodb
