一般jre环境下的汉子拼音转换

package com.inventec.FetchFirstLetter;

import java.util.Comparator;

import net.sourceforge.pinyin4j.PinyinHelper;

public class PinyinComparator implements Comparator {
	 
    public  int compare(Object o1, Object o2) {   
        String key1 = o1.toString();
        String key2 = o2.toString();
        for (int i = 0; i < key1.length() && i < key2.length(); i++) {   
  
            int codePoint1 = key1.charAt(i);   
            int codePoint2 = key2.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 key1.length() - key2.length();   
    }   
 /*
  * 源码 
  
    public String pinyin (char c) {   
        
    	String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(c);   
        if (pinyins == null) {   
        	
        	return null;   //如果转换结果为空,则返回null
        }  
        return pinyins[0];   //如果为多音字返回第一个音节
    }
    
 */
    
 /*
  * 让函数无处理时返回原字符 
  */
    
    public static String pinyin (char c) {   
        
    	String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(c);   
        if (pinyins == null) {   
        	StringBuffer sb = new StringBuffer();
        	sb.append(c);
        	return sb.toString();   //如果转换结果为空,则返回原char c
        }  
        return pinyins[0];   //如果为多音字返回第一个音节
    }

 /*
  * 调用封装成接收字符串
  */
    public static String myPinyin(String str) {
    	
    	char[] strChar = str.toCharArray();
    	StringBuffer sb = new StringBuffer();
    	for(int i=0;i<strChar.length;i++) {
    		if(strChar[i] > 126 || strChar[i] < 27)
    			sb.append(pinyin(strChar[i]).substring(0, pinyin(strChar[i]).length()-1));
    		else sb.append(pinyin(strChar[i]));
    	}
    	return sb.toString();
    	
    }
}


你可能感兴趣的:(一般jre环境下的汉子拼音转换)