go 字符串修改的操作代码

来自:网络
时间:2022-06-18
阅读:

字符串和切片(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
}
返回顶部
顶部