java字符串 替换问题
String str ="jhuywy48r在74yhf47tf6中7dgc782有3y..."; 后面还有几百个汉字 汉字的个数不确定
我想把里面所有的 汉字 换成对应的 拼音
我已经有 汉字 和 拼音 的 替换数组了
那怎么有效率的 用这个数组 去把里面的汉字 替换掉了?
[解决办法]
1、把汉字和拼音做成一个通过对汉字 做一个哈希表
2、for循环遍历 ,然后替换
俺只会笨办法 ,静等高效方法...
[解决办法]
可以用正则,发现是中文就拿对应的拼音替换。
[解决办法]
public static void main(String[] args) throws Exception { String str ="jhuywy48r在74yhf47tf6中7dgc782有3y..."; StringBuffer buf = new StringBuffer(); Pattern p = Pattern.compile("[\u4e00-\u9fa5]"); Matcher m = p.matcher(str); while(m.find()){ String chinese = m.group();//匹配出的中文 String pinyin = "pinyin";//在你的中文与拼音对应中找到对应拼音。 m.appendReplacement(buf, pinyin); } m.appendTail(buf); System.out.println(buf.toString()); }
[解决办法]