???????? 最近碰到了一面試題:一個(gè)字符串中如何得到漢字的個(gè)數(shù)?比如"adf我jk愛sdf莫能助lkka",要求寫一個(gè)方法得出其中漢字的個(gè)數(shù),并取得這些漢字。
??????? 自己想了半天沒做出來,在CSDN發(fā)了個(gè)貼子得到了答案,在此感謝CSDN的網(wǎng)友,huyc_fly() ,希望他不會(huì)介意我把他的方法發(fā)出來與大家,也許大家還有別的解決方法,非常期望跟大家討論.
??????? 實(shí)現(xiàn)代碼如下:
??public class TestChineseChar {
??public static void main(String[] args) {
??TestChineseChar t = new TestChineseChar();
??t.getChineseChar();
?}
?public void getChineseChar() {
??String str = "adf我jk愛sdf莫能助lkka";
??StringBuffer sb = new StringBuffer();
??String tempStr;
??int count = 0;
??for (int i = 0; i < str.length(); i++) {
???tempStr = String.valueOf(str.charAt(i));
???if (tempStr.getBytes().length == 2) {
????sb.append(tempStr);
????count++;
???}
??}
??System.out.println("the count of chinese characters in the String is :"
????+ count);
??System.out.println(sb.toString());
?}
}