在Java中搜索/排序和字符串编码(Searching/sorting and string encoding in Java)

编程入门 行业动态 更新时间:2024-10-24 16:23:17
在Java中搜索/排序和字符串编码(Searching/sorting and string encoding in Java)

我正在用Java构建一个用于项目的小型内存文件系统,我目前正在使用二进制搜索来定位节点,但是当我在查找错误时,我注意到带有大写字母的节点将被排序到列表的开头因为他们在Unicode中的地位。 这仍然可以用于查找具有二进制搜索的节点,但是它们应该表示按字母顺序排序的列表,这是不可接受的,例如:

Hosts.txt abc home settings.txt

我在想什么是最简单的解决方案(理论上)将字符串放在字符集中,字符布局如下:

aAbBcCdDeEfFgGhHiIjJkKlLmM... and so on with special characters and such included

有没有办法轻松地做到这一点或者更好的方式?

I'm building a small in-memory file system in Java for a project, I'm currently using a binary search to locate nodes but when I was looking for bugs I noticed that nodes with capitals would be sorted to the beginning of the list because of their position in Unicode. This still works fine for finding nodes with binary search but while they should represent an alphabetically sorted list this is not acceptable, for example:

Hosts.txt abc home settings.txt

What I'm thinking would be the easiest solution (theoretically) would be to have the strings in a charset with the characters laid out something like this:

aAbBcCdDeEfFgGhHiIjJkKlLmM... and so on with special characters and such included

Is there some way to do this easily or perhaps a better way?

最满意答案

你应该定义自己的比较器:

public class MyStringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { int caseIgnoreResult = s1.compareToIgnoreCase(s2); if (caseIgnoreResult == 0) { return s1.compareTo(s2); } else { return caseIgnoreResult; } } }

我希望这有帮助。

You should define your own comparator:

public class MyStringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { int caseIgnoreResult = s1.compareToIgnoreCase(s2); if (caseIgnoreResult == 0) { return s1.compareTo(s2); } else { return caseIgnoreResult; } } }

I hope this helps.

更多推荐

本文发布于:2023-08-03 14:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1389353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Searching   Java   encoding   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!