字符串和切片(string and slice)
string底层就是一个byte的数组,因此,也可以进行切片操作。
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中字符。需要如下操作:
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)
}
修改中文字符串
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:转换为[]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
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)