使用非西方字符对字符串进行排序 [英] Sorting String with non-western characters

查看:126
本文介绍了使用非西方字符对字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印所有可用语言的已排序波兰语名称。

I wanted to print sorted Polish names of all available languages.

import java.util.*;

public class Tmp
{
  public static void main(String... args)
  {
    Locale.setDefault(new Locale("pl","PL"));
    Locale[] locales = Locale.getAvailableLocales();
    ArrayList<String> langs = new ArrayList<String>();
    for(Locale loc: locales) {
      String  lng = loc.getDisplayLanguage();
      if(!lng.trim().equals("") && ! langs.contains(lng)){
        langs.add(lng);
      }
    }
    Collections.sort(langs);
    for(String str: langs){
      System.out.println(str);
    }
  }
}

不幸的是我遇到了问题排序部分。
输出为:

Unfortunately I have issue with the sorting part. The output is:

:
:
kataloński
koreański
litewski
macedoński
:
:
węgierski
włoski
łotewski

不幸的是波兰语ł l 之后和<$ c之前$ c> m 所以输出应为:

Unfortunately in Polish ł comes after l and before m so the output should be:

:
:
kataloński
koreański
litewski
łotewski
macedoński
:
:
węgierski
włoski

我怎样才能做到这一点?是否存在一种通用的非语言相关方法(比如我现在想要显示它并使用另一种排序规则在另一种语言中排序)。

How can I accomplish that? Is there an universal non-language-dependent method (say I now want to display this and sort in another language with another sorting rules).

推荐答案

您应该将Collat​​or传递给sort方法:

You should pass a Collator to the sort method:

// sort according to default locale
Collections.sort(langs, Collator.getInstance());

默认排序顺序由字符串中的Unicode代码点定义,这不是正确的字母顺序任何语言。

The default sort order is defined by the Unicode codepoints in the string, and that's not the correct alphabetical order in any language.

这篇关于使用非西方字符对字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆