zoukankan      html  css  js  c++  java
  • 获取汉字串拼音首字母,英文字符不变

    package com.sprucetec.tms.utils;

    import net.sourceforge.pinyin4j.PinyinHelper;
    import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
    import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
    import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
    import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
    import org.apache.commons.lang.StringUtils;

    /**
    * 描述: 拼音工具类
    *
    * @author yangweiqiang
    * @date 2016/8/9
    */
    public class PinYinUtils {

    /**
    * 获取汉字串拼音首字母,英文字符不变
    *
    * @param chinese 汉字串
    * @param caseType 大写 or 小写
    * @return 汉语拼音首字母
    */
    public static String getFirstSpell(String chinese, HanyuPinyinCaseType caseType) {
    if (StringUtils.isBlank(chinese)) {
    return null;
    }

    StringBuffer sb = new StringBuffer();
    char[] arr = chinese.toCharArray();

    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(caseType);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

    for (int i = 0; i < arr.length; i++) {
    if (arr[i] > 128) {
    try {
    String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
    if (temp != null) {
    sb.append(temp[0].charAt(0));
    }
    } catch (BadHanyuPinyinOutputFormatCombination e) {
    e.printStackTrace();
    }
    } else {
    sb.append(arr[i]);
    }
    }
    return sb.toString().replaceAll("\W", "").trim();
    }

    }
  • 相关阅读:
    如何将一个类改造为线程安全
    50行代码实现缓存,JAVA内存模型原理
    Qt 解压/压缩文件
    QT学习笔记—1
    在http编程的门口飞牛网自动下单,查单
    QList 排序
    Qt 打开指定的文件
    spoj 375 query on a tree 题解
    uva 11388 GCD LCM题解
    uva 1476 Error Curves 题解
  • 原文地址:https://www.cnblogs.com/duyinqiang/p/6909847.html
Copyright © 2011-2022 走看看