通过pinyin4j.jar将(汉字拼音混合字符串)转化成字母首字母
通过pinyin4j.jar将(汉字拼音混合字符串)转化成字母首字母
例如
我的中国心 ==》 wdzgx
我的中国心ya ==》 wdzgxya
woai我的中国 ==》 woaiwdzg
1、首先引入pinyin4j.jar
2、主要代码
package lpc.com.project20170106; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; 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 MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String shouzimu = getFirstSpell("我的中国心feng"); Log.e(TAG, "onCreate: " + shouzimu); } public static String getFirstSpell(String chinese) { StringBuffer pybf = new StringBuffer(); char[] arr = chinese.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (char curchar : arr) { if (curchar > 128) { try { String[] temp = PinyinHelper.toHanyuPinyinStringArray(curchar, defaultFormat); if (temp != null) { pybf.append(temp[0].charAt(0)); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pybf.append(curchar); } } return pybf.toString().replaceAll("\\W", "").trim(); } }