日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

go?字符串修改的操作代碼_Golang

作者:看,未來 ? 更新時間: 2022-08-10 編程語言

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

原文鏈接:https://blog.csdn.net/qq_43762191/article/details/125339575

欄目分類
最近更新