gpt4 book ai didi

arrays - 在groovy中按字母顺序对字符串数组进行排序

转载 作者:行者123 更新时间:2023-12-02 00:54:46 26 4
gpt4 key购买 nike

所以我一直在学习在 Groovy 中使用数组。我想知道如何按字母顺序对字符串数组进行排序。我的代码当前接受用户输入的字符串并按顺序和逆序打印它们:

System.in.withReader {
def country = []
print 'Enter your ten favorite countries:'
for (i in 0..9)
country << it.readLine()
print 'Your ten favorite countries in order/n'
println country //prints the array out in the order in which it was entered
print 'Your ten favorite countries in reverse'
country.reverseEach { println it } //reverses the order of the array

我该如何按字母顺序打印它们?

最佳答案

sort()是你的 friend 。

country.sort()将排序 country按字母顺序,变异 country正在进行中。 country.sort(false)将排序 country按字母顺序,返回排序后的列表。

def country = ['Ireland', 'Iceland', 'Hungary', 'Thailand']
assert country.sort() == ['Hungary', 'Iceland', 'Ireland', 'Thailand']
assert country == ['Hungary', 'Iceland', 'Ireland', 'Thailand']

country = ['Ireland', 'Iceland', 'Hungary', 'Thailand']
assert country.sort(false) == ['Hungary', 'Iceland', 'Ireland', 'Thailand']
assert country == ['Ireland', 'Iceland', 'Hungary', 'Thailand']

关于arrays - 在groovy中按字母顺序对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20386377/

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