01.public class StringTest {
02.
03. /**
04. * 该方法只是简单的查看字符串中有没有汉字和汉字的个数
05. * @param s
06. */
07. public void testMethod1(String s){
08. int bytesLength = s.getBytes().length;
09. int sLength = s.length();
10. int hasNum = bytesLength - sLength;
11. if(hasNum==0){
12. System.out.println("字符串中不含有汉字。");
13. }
14. else if(hasNum>0){
15. System.out.println("含有 "+hasNum+" 个汉字。");
16. }
17. }
18.
19. /**
20. * 该方法中除了查看字符串中有没有汉字和汉字的个数外还能把汉字的内容显示出来
21. * @param s
22. */
23. public void testMethod2(String s){
24. StringBuffer sb = new StringBuffer();
25. String tempStr ;
26. int count=0;
27. for(int i = 0;i<s.length();i++){
28. tempStr = String.valueOf(s.charAt(i));
29. if(tempStr.getBytes().length==2){
30. count++;
31. sb.append(tempStr+" ");
32. }
33. }
34. System.out.println("字符串中有"+count+"个汉字。");
35. System.out.println(sb.toString());
36. }
37.
38. /**
39. * 该方法中除了查看字符串中有没有汉字和汉字的个数外还能把汉字的内容显示出来
40. * @param s
41. */
42. public void testMethod3(String s){
43. int count = 0;
44. char[] cStr = s.toCharArray();
45. for(int i = 0,j = cStr.length ; i < j; i++){
46. if(cStr[i] > 127){
47. count++;
48. System.out.print(cStr[i]+" ");
49. }
50.
51. }
52. System.out.println("字符串中有"+count+"个汉字");
53. }
54.
55. public static void main(String[] args){
56. StringTest st = new StringTest();
57. String s ="dd我是addf中国人";
58. st.testMethod1(s);
59. st.testMethod2(s);
60. st.testMethod3(s);
61.
62. }
63.
64.
65.}