go 字符串修改

字符串和切片(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)
}

猜你喜欢

转载自blog.csdn.net/qq_43762191/article/details/125339575