字符串和切片(string and slice)
string底层就是一个byte的数组,因此,也可以进行切片操作。
1
2
3
4
5
6
7
8
|
package main import ( "fmt" ) func main(){ str := "hello world" s1 := str[ 0 : 5 ] fmt. Println (s1) s2 := str[ 6 :] fmt. Println (s2)} |
输出结果:
hello
world
修改英文字符串
string本身是不可变的,因此要改变string中字符。需要如下操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package main import ( "fmt" ) func main() { str := "Hello world" s := [] byte (str) //中文字符需要用[]rune(str) s[ 6 ] = 'G' s = s[: 8 ] s = append (s, '!' ) str = string (s) fmt. Println (str) } |
修改中文字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package main import ( "fmt" ) func main() { str := "你好,世界!hello world!" s := [] rune (str) s[ 3 ] = '啊' s[ 4 ] = '锋' s[ 12 ] = 'g' s = s[: 14 ] str = string (s) fmt. Println (str) } |
补充知识:Go语言实现修改字符串的三种方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/* 修改字符串 注意:字符串是无法被修改的,只能复制原字符串,在复制的版本上修改 方法1:转换为[]byte() 方法2:转换为[]rune() 方法3:新字符串代替原字符串的子字符串,用strings包中的strings.Replace() */ func main() { //方法1 s1 := "abcdefgabc" s2 := [] byte (s1) s2[ 1 ] = 'B' fmt. Println ( string (s2)) //aBcdefgabc //方法2 s3 := [] rune (s1) s3[ 1 ] = 'B' fmt. Println ( string (s3)) //aBcdefgabc //方法3 new := "ABC" old := "abc" s4 := strings.Replace(s1, old, new , 2 ) fmt. Println (s4) //ABCdefgABC } |
到此这篇关于go 字符串修改的文章就介绍到这了,更多相关go 字符串修改内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_43762191/article/details/125339575