support pinyin search
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
package com.imyeyu.api.util;
|
||||
|
||||
import me.majiajie.tinypinyin.Pinyin;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/// 拼音搜索工具
|
||||
///
|
||||
/// @author Codex
|
||||
/// @since 2026-08-21
|
||||
public final class PinyinUtil {
|
||||
|
||||
private PinyinUtil() {
|
||||
}
|
||||
|
||||
/// 转换为无声调全拼
|
||||
///
|
||||
/// @param value 原始文字
|
||||
/// @return 无声调全拼
|
||||
public static String full(String value) {
|
||||
return convert(value, false, false);
|
||||
}
|
||||
|
||||
/// 转换为拼音首字母
|
||||
///
|
||||
/// @param value 原始文字
|
||||
/// @return 拼音首字母
|
||||
public static String initial(String value) {
|
||||
return convert(value, true, false);
|
||||
}
|
||||
|
||||
/// 转换为首字全拼、后续字首字母的混合拼音
|
||||
///
|
||||
/// @param value 原始文字
|
||||
/// @return 混合拼音
|
||||
public static String mixed(String value) {
|
||||
return convert(value, false, true);
|
||||
}
|
||||
|
||||
private static String convert(String value, boolean initial, boolean mixed) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder result = new StringBuilder(value.length());
|
||||
boolean first = true;
|
||||
for (char character : value.toCharArray()) {
|
||||
if (Character.isWhitespace(character)) {
|
||||
continue;
|
||||
}
|
||||
String pinyin = Pinyin.toPinyin(character).toLowerCase(Locale.ROOT);
|
||||
if (pinyin.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (initial || (mixed && !first)) {
|
||||
result.append(pinyin.charAt(0));
|
||||
} else {
|
||||
result.append(pinyin);
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user