java实现中文字符转拼音,并实现首字符大写

本文介绍了一种使用pinyin4j库将中文字符串转换为帕斯卡命名法拼音的方法。通过设置汉语拼音输出格式,实现了首字母大写,其余字母小写的转换效果,适用于Java项目的名称规范化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom.xml进行配置
	<!--Pinyin -->
	<dependency>
		<groupId>com.belerweb</groupId>
		<artifactId>pinyin4j</artifactId>
		<version>2.5.1</version>
	</dependency>
package com.yoyowang.framework.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;


public class HanyupinyinUtil {
    /**
     * @Description 中文转拼音,帕斯卡命名法,每个首字母大写
     *
     * @param chinese 中文字符
     *
     * @return String 帕斯卡命名法的拼音
     *
     */
    public static String getPascalString(String chinese) {
        String pascalSpell = "";// 返回的拼音
        try {
            char[] cl_chars = chinese.trim().toCharArray();
            // 大写样式
            HanyuPinyinOutputFormat upperFormat = new HanyuPinyinOutputFormat();
            upperFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);// 大写
            upperFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
            // 小写样式
            HanyuPinyinOutputFormat lowerFormat = new HanyuPinyinOutputFormat();
            lowerFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 小写
            lowerFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
            for (int i = 0; i < cl_chars.length; i++) {
                String str = String.valueOf(cl_chars[i]);
                if (str.matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母大写,其他字母小写
                    pascalSpell += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], upperFormat)[0].substring(0, 1);
                    pascalSpell += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], lowerFormat)[0].substring(1);
                } else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
                    pascalSpell += cl_chars[i];
                } else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母
                    pascalSpell += cl_chars[i];
                } else {// 否则不转换
                    pascalSpell += cl_chars[i];//如果是标点符号的话,带着
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        return pascalSpell;
    }
    
    public static void main(String[] args) {
        System.out.println(getPascalString("嗯哼"));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值