赞
踩
话不多说,上代码:
- package cn.jiangshuai.personManage;
-
- import java.util.Scanner;
-
- 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;
-
- /**
- * 中文汉字转拼音工具类
- * @author JSYH
- *
- */
- public class Main {
- public static void main(String[] args) {
- // System.out.println("中国 首字母大写:"+toFirstChar("中国").toUpperCase());
- // System.out.println("中国 转成拼音:"+toPinyin("中国"));
- StringBuilder sBuilder = new StringBuilder();
- System.out.println("请输入中文......");
- Scanner inScanner = new Scanner(System.in);
- while(inScanner.hasNextLine()) {
- sBuilder.append(inScanner.nextLine());
- if(inScanner.nextLine().equals("over")) { //用于控制结束输入的逃逸字符
- break;
- }
- }
- System.out.println("处理之后的输入字符串......");
- //System.out.println(sBuilder.toString().replaceAll("[^(0-9)]", ""));
- System.out.println(sBuilder.toString().replaceAll("[^(\\u4e00-\\u9fa5)]", "")); //借助正则表达式过滤掉非汉字的内容
- System.out.println("转换结果......");
- System.out.println(toFirstChar(sBuilder.toString().replaceAll("[^(\\u4e00-\\u9fa5)]", "")));
- System.out.println(toPinyin(sBuilder.toString().replaceAll("[^(\\u4e00-\\u9fa5)]", "")));
- }
-
- /**
- * 输入中文字符串 输出各汉字的首字母组成的字符串
- * @param chinese
- * @return
- */
- public static String toFirstChar(String chinese) {
- String pinyinString = "";
- char[] newchar = chinese.toCharArray();
- HanyuPinyinOutputFormat hypy = new HanyuPinyinOutputFormat();
- hypy.setCaseType(HanyuPinyinCaseType.LOWERCASE);
- //hypy.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
- hypy.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
- for(int i = 0;i < newchar.length;i++) {
- if(newchar[i]>128) {
- try {
- pinyinString += PinyinHelper.toHanyuPinyinStringArray(newchar[i], hypy)[0].charAt(0);
- } catch (BadHanyuPinyinOutputFormatCombination e) {
- e.printStackTrace();
- }
- }else {
- pinyinString += newchar[i];
- }
- }
- return pinyinString;
- }
-
-
- /**
- * 输入中文字符串 输出各汉字的拼音全拼
- * @param chinese
- * @return
- */
- public static String toPinyin(String chinese) {
- String pinyinString = "";
- char[] newchar = chinese.toCharArray();
- HanyuPinyinOutputFormat hypy = new HanyuPinyinOutputFormat();
- hypy.setCaseType(HanyuPinyinCaseType.LOWERCASE);
- hypy.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
- for(int i = 0;i < newchar.length;i++) {
- if(newchar[i]>128) {
- try {
- pinyinString += PinyinHelper.toHanyuPinyinStringArray(newchar[i], hypy)[0];
- } catch (BadHanyuPinyinOutputFormatCombination e) {
- e.printStackTrace();
- }
- }else {
- pinyinString += newchar[i];
- }
- }
- return pinyinString;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。