gpt4 book ai didi

'sort -V' 的 Java 替代方案

转载 作者:行者123 更新时间:2023-12-01 15:33:10 26 4
gpt4 key购买 nike

我正在寻找 shell 命令的纯 java 替代方案:sort -V。我正在寻找一个可以简单插入的比较器类。sort -V 命令只是使用版本系统对文件进行排序(即 3.2.0-113.2.0-1 大 10,不是 0.1 大)。

提前致谢!

最佳答案

我曾经写过一个通用的“像人类一样”的比较器。我没有代码可以显示,但想法是像这样分割每个字符串:

fragments = empty string collection
buffer = first character of the string
if character is digit, mode = NUMBER, else mode = TEXT
while there are characters left
c = next character
if c is digit and mode is NUMBER, add character to buffer
else if c is not a digit and mode is TEXT, add character to buffer
else
add contents of buffer (as string) to the fragments collection,
flip mode from TEXT to NUMBER or vice versa
buffer = c
end if
end while
add remaining contents of buffer to fragments

现在您已经有了一个子字符串列表,其中包含交替的数字片段和非数字片段。 (例如 something-1.0.26.jar 将变为 { 'something-', '1', '.', '0', '.', '26', '.jar ' })

如果对两个字符串都执行此操作,则可以编写一个比较器来逐一比较这对片段:如果都是数字,则进行数字比较,如果都是文本,则进行字符串比较,如果其中一个是数字,则进行数字比较其他是文本,数字优先。

我知道这比您想要的要多得多,但在许多情况下这是一段非常有用的代码。

关于 'sort -V' 的 Java 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9317504/

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