gpt4 book ai didi

按字符和长度对字符串进行排序

转载 作者:IT老高 更新时间:2023-10-28 13:40:10 25 4
gpt4 key购买 nike

在我的 Android 应用程序中,我正在尝试按 1、2、3..etc 的顺序对公交路线标签进行排序。

为此我正在使用它

Collections.sort(directions, Comparator { lhs, rhs ->
var obj1 = lhs.short_names.firstOrNull() ?: ""
var obj2 = rhs.short_names.firstOrNull() ?: ""

if (obj1 === obj2) {
obj1 = lhs.headsigns.firstOrNull() ?: ""
obj2 = rhs.headsigns.firstOrNull() ?: ""
if (obj1 === obj2) {
return@Comparator 0
}
obj1.compareTo(obj2)
} else {
obj1.compareTo(obj2)
}

我遇到的问题是对它们进行排序,但会遇到以下问题1、2、3、30、31、4、5

我应该如何更改它以获得正确的顺序。

最佳答案

如果你只需要一个简单的数字比较,你可以这样做。

directions.sortWith(Comparator { lhs, rhs ->
val i1 = lhs.toInt()
val i2 = rhs.toInt()
when {
i1 < i2 -> -1
i1 > i2 -> 1
else -> 0
}
})

作为 hotkey指出上面的代码可以替换为看起来更简单的几乎相同的实现。

directions.sortBy { it.toInt() }

该算法的通用版本称为字母排序,详细描述here .我制作了这个算法的 Kotlin 端口,你可以使用它。它比您需要的更复杂,但它会解决您的问题。

class AlphanumComparator : Comparator<String> {
override fun compare(s1: String, s2: String): Int {
var thisMarker = 0
var thatMarker = 0
val s1Length = s1.length
val s2Length = s2.length

while (thisMarker < s1Length && thatMarker < s2Length) {
val thisChunk = getChunk(s1, s1Length, thisMarker)
thisMarker += thisChunk.length

val thatChunk = getChunk(s2, s2Length, thatMarker)
thatMarker += thatChunk.length

// If both chunks contain numeric characters, sort them numerically.
var result: Int
if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) {
// Simple chunk comparison by length.
val thisChunkLength = thisChunk.length
result = thisChunkLength - thatChunk.length
// If equal, the first different number counts.
if (result == 0) {
for (i in 0..thisChunkLength - 1) {
result = thisChunk[i] - thatChunk[i]
if (result != 0) {
return result
}
}
}
} else {
result = thisChunk.compareTo(thatChunk)
}

if (result != 0) {
return result
}
}

return s1Length - s2Length
}

private fun getChunk(string: String, length: Int, marker: Int): String {
var current = marker
val chunk = StringBuilder()
var c = string[current]
chunk.append(c)
current++
if (isDigit(c)) {
while (current < length) {
c = string[current]
if (!isDigit(c)) {
break
}
chunk.append(c)
current++
}
} else {
while (current < length) {
c = string[current]
if (isDigit(c)) {
break
}
chunk.append(c)
current++
}
}
return chunk.toString()
}

private fun isDigit(ch: Char): Boolean {
return '0' <= ch && ch <= '9'
}
}

要使用这个 Comparator 只需调用

directions.sortWith(AlphanumComparator())

如果您不需要在 Kotlin 中对其进行编码,您可以在 Dave Koelle's page 上获取原始 Java 版本。 .该算法的 Kotlin 版本也可以在 GitHub 上找到。 .

关于按字符和长度对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36506899/

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