perfectStep := ",1,3,5,4,2," 结果不变保存从小到大
时间: 2023-08-29 16:06:10 浏览: 151
满足加法的按从小到大数组存储
5星 · 资源好评率100%
你可以将前面所述的代码稍作修改,将最终的排序结果保存回 `perfectStep` 变量中,示例如下:
```
import (
"fmt"
"sort"
"strconv"
"strings"
)
func main() {
perfectStep := ",1,3,5,4,2,"
strSlice := strings.Split(perfectStep, ",")
intSlice := make([]int, 0, len(strSlice)-1)
for _, str := range strSlice {
if str != "" {
num, err := strconv.Atoi(str)
if err == nil {
intSlice = append(intSlice, num)
}
}
}
sort.Ints(intSlice)
intSliceStr := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(intSlice)), ","), "[]")
perfectStep = "," + intSliceStr + ","
fmt.Println(perfectStep)
}
```
在排序后的整数类型切片转换成字符串类型的过程中,我们将其存储在了 `intSliceStr` 变量中,最后再将其保存回 `perfectStep` 变量中。输出结果为:`",1,2,3,4,5,"`。
阅读全文