gpt4 book ai didi

go - 交换两个字符串(Golang)

转载 作者:IT王子 更新时间:2023-10-29 02:25:35 34 4
gpt4 key购买 nike

我目前正在学习 Golang,我决定编写一些简单的算法来学习语法。我希望它还没有答案,但我没有找到它..

我有一个交换字符串的问题

func swap(str1, str2 string) {
/*
* Also possible :
* str1, str2 = str2, str1
*/
// str1, str2 = str2, str1
tmp := str1
str1 = str2
str2 = tmp
}

func main() {
a := "World !"
b := "Hello"
swap(a, b)
fmt.Printf("a=%s\nb=%s\n", a, b)
}

为什么这段代码不起作用?

最佳答案

交换 str1str2 不会改变 ab,因为它们是 的副本>ab。使用指针:

func swap(str1, str2 *string) {
*str1, *str2 = *str2, *str1
}

func main() {
a := "salut"
b := "les gens"
swap(&a, &b)
fmt.Printf("a=%s\nb=%s\n", a, b)
}

http://play.golang.org/p/Qw0t5I-XGT

关于go - 交换两个字符串(Golang),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439281/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com