参阅:
https://www.cnblogs.com/liangblog/p/13825427.html
maven
<dependencies> <dependency> <groupId>com.github.stuxuhai</groupId> <artifactId>jpinyin</artifactId> <version>1.1.8</version> </dependency>
import com.github.stuxuhai.jpinyin.ChineseHelper; import com.github.stuxuhai.jpinyin.PinyinFormat; import com.github.stuxuhai.jpinyin.PinyinHelper; public class PinyinHelperTest { /** * 转换为每个汉字对应拼音首字母字符串 * @param pinYinStr 需转换的汉字 * @return 拼音字符串 */ public String changeToGetShortPinYin(String pinYinStr){ String tempStr = null; try { tempStr = PinyinHelper.getShortPinyin(pinYinStr); } catch (Exception e) { e.printStackTrace(); } return tempStr; } public boolean checkPinYin(char pinYinStr){ boolean check = false; try { check = PinyinHelper.hasMultiPinyin(pinYinStr); } catch (Exception e) { e.printStackTrace(); } return check; } public static void main(String[] args) { String str = "大夫"; PinyinHelperTest jp = new PinyinHelperTest(); // System.out.println(jp.changeToMarkPinYin(str)); // System.out.println(jp.changeToTonePinYin(str)); //有空格 // System.out.println(jp.changeToSimplified(str)); System.out.println(jp.checkPinYin('行')); System.out.println(jp.changeToGetShortPinYin(str)); } }
建议在数据库中,增加一个字段,作为首字母的存储。