gpt4 book ai didi

go - 如何在 Go 中使用排序包反转字符串 slice ?

转载 作者:数据小太阳 更新时间:2023-10-29 03:46:43 24 4
gpt4 key购买 nike

strArr := []string{"one", "two", "three"}
// expected Result : ["three", "two, "one"]

我想使用 sort package 来做到这一点

最佳答案

Comment: Something like this in JavaScript : strArr.reverse(). – Jackal


JavaScript: Array.prototype.reverse()

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.


例如,

package main

import (
"fmt"
)

func reverse(s []string) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}

func main() {
strArr := []string{"one", "two", "three"}
fmt.Println(strArr)
reverse(strArr)
fmt.Println(strArr)
reverse(strArr)
fmt.Println(strArr)
}

Playground :https://play.golang.org/p/087uE00WROI

输出:

[one two three]
[three two one]
[one two three]

关于go - 如何在 Go 中使用排序包反转字符串 slice ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54376250/

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