Get the first letter based on Chinese characters in Java

Table of contents

1. Introduce dependencies

2. Code implementation

3. Functional testing


1. Introduce dependencies

        There are two ways to implement the function of obtaining the first letter of Chinese characters in Java, one is to use the third-party library Pinyin4j and the RuleBasedCollator class that comes with Java . Here is a brief description of how to use the third-party library Pinyin4j;

        First introduce relevant dependencies into the project:

<dependency>
    <groupId>com.belerweb</groupId>
    <artifactId>pinyin4j</artifactId>
    <version>2.5.1</version>
</dependency>

2. Code implementation

        Create the PinYinUtil tool class and combine the methods provided by Pinyyin4j to write specific function implementations;



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();
    }


}

        In the above function code: the getPinYinHeadChar()  method is to get the first letter according to the character, which mainly uses  the toHanguPinyinStringArray()  method in Pinyin4j to extract the first letter of a single character and then splice the result. Finally, comment the code to choose whether the result should retain spaces and convert the letter size write function.

3. Functional testing

The result retains spaces and is converted to uppercase:

The result is stripped of spaces and converted to lowercase:

Guess you like

Origin blog.csdn.net/weixin_45151960/article/details/133176794