汉字转拼音工具
import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.stuxuhai.jpinyin.PinyinException; import com.github.stuxuhai.jpinyin.PinyinFormat; import com.github.stuxuhai.jpinyin.PinyinHelper; /** * 汉子转拼音 * * @author: Nemo */ public class JPinyinUtils { private static final Logger log = LoggerFactory.getLogger(JPinyinUtils.class); private final static String PINYIN_SEPARATOR = ","; /** * @Description: 将中文转换为拼音(每个汉子的拼音逗号隔开):微迈->wei,mai * @param str * @return */ public static String convertToPY(String str) { if (StringUtil.isEmpty(str)) { return str; } try { return PinyinHelper.convertToPinyinString(str, PINYIN_SEPARATOR, PinyinFormat.WITHOUT_TONE); } catch (PinyinException e) { log.error("拼音转换错", e); } return str; } /** * 转换为简拼大写,中间用逗号隔开:微迈->W,M * * @param str * @return */ public static String covertToJP(String str) { if (StringUtil.isEmpty(str)) { return str; } try { String jp = PinyinHelper.getShortPinyin(str); if (StringUtils.isNotBlank(jp)) { jp = StringUtil.insertSeparator(jp, PINYIN_SEPARATOR); } return jp.toUpperCase(Locale.getDefault()); } catch (PinyinException e) { log.error("拼音转换错", e); } return str; } /** * 转换为简拼大写,中间用逗号隔开:微迈->W,M * * @param str * @return */ public static String covertToJPWithNonSeparator(String str) { if (StringUtil.isEmpty(str)) { return str; } try { String jp = PinyinHelper.getShortPinyin(str); return jp.toUpperCase(Locale.getDefault()); } catch (PinyinException e) { log.error("拼音转换错", e); } return str; } /** * 将中文转换为拼音:微迈->微迈 * * @param str * @return */ public static String covertToPinYin(String str) { if (StringUtil.isEmpty(str)) { return str; } try { return PinyinHelper.convertToPinyinString(str, "", PinyinFormat.WITHOUT_TONE); } catch (PinyinException e) { log.error("拼音转换错", e); } return str; }
maven 依赖
<dependency> <groupId>com.github.stuxuhai</groupId> <artifactId>jpinyin</artifactId> <version>1.1.8</version> </dependency>