目录
在Java中想要实现根据中文汉字获取首字母的功能有两种途径,分别是使用第三方库Pinyin4j和Java自带的RuleBasedCollator类实现,这里大概讲述关于第三方库Pinyin4j的使用方式;
首先在项目中引入相关依赖:
-
com.belerweb -
pinyin4j -
2.5.1
创建PinYinUtil工具类,结合Pinyyin4j提供的方法来编写具体功能实现;
-
-
- import net.sourceforge.pinyin4j.PinyinHelper;
- import org.springframework.stereotype.Component;
-
- /**
- * @Author: ljh
- * @ClassName PinYinUtil
- * @Description TODO
- * @date 2023/4/27 17:19
- * @Version 1.0
- */
- @Component
- public class PinYinUtil {
-
-
-
- /**
- * @Author: ljh
- * @Description: 提取每个字符的首字母(大写)
- * @DateTime: 17:20 2023/4/27
- * @Params:
- * @Return
- */
- public static String getPinYinHeadChar(String str) {
- if (str == null || str.trim().equals("")) {
- return "";
- }
- String convert = "";
- for (int j = 0; j < str.length(); j++) {
- char word = str.charAt(j);
- // 提取字符的首字母
- String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
- if (pinyinArray != null) {
- convert += pinyinArray[0].charAt(0);
- } else {
- convert += word;
- }
- }
- // 去除字符中包含的空格
- // convert = convert.replace(" ","");
- // 字符转小写
- // convert.toLowerCase();
- return convert.toUpperCase();
- }
-
-
- }
上述功能代码中:getPinYinHeadChar() 方法就是根据字符获取首字母,其中主要是使用Pinyin4j中的 toHanguPinyinStringArray() 方法对单个字符提取首字母然后拼接结果,最后注释代码可以选择结果是否保留空格及转换字母大小写功能。
结果保留空格并转大写:
结果去除空格并转小写:
