拼音排序,按拼音排序

來源:互聯網
上載者:User

拼音排序,按拼音排序
package com.example.f; import java.util.Comparator;import net.sourceforge.pinyin4j.PinyinHelper; public class PinyinComparator implements Comparator { public int compare(String o1, String o2) { for (int i = 0; i < o1.length() && i < o2.length(); i++) { int codePoint1 = o1.charAt(i); int codePoint2 = o2.charAt(i); if (Character.isSupplementaryCodePoint(codePoint1) || Character.isSupplementaryCodePoint(codePoint2)) { i++; } if (codePoint1 != codePoint2) { if (Character.isSupplementaryCodePoint(codePoint1) || Character.isSupplementaryCodePoint(codePoint2)) { return codePoint1 - codePoint2; } String pinyin1 = pinyin((char) codePoint1); String pinyin2 = pinyin((char) codePoint2); if (pinyin1 != null && pinyin2 != null) { // 兩個字元都是漢字 if (!pinyin1.equals(pinyin2)) { return pinyin1.compareTo(pinyin2); } } else { return codePoint1 - codePoint2; } } } return o1.length() - o2.length(); } /** * 字元的拼音,多音字就得到第一個拼音。不是漢字,就return null。 */ private static String pinyin(char c) { String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(c); if (pinyins == null) { return null; } return pinyins[0]; } } 需要倒入pinyin4j-2.5.0.jar包!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.