• getBytes方法


     字符串中的字符变成一位一位的01比特流

    一个英文字符占8比特,也就是一个字节

    一个中文字符占24比特,也就是3个字节(其实不同编码方式,占几个字节不一样,我们这里采取的UTF-8编码方式,具体可以看下图:)

    而byte[  ]  byte数组里面存的就是每个字节(8位)表示的数字 

    所以一个英文字符(8比特)只需要1个byte数组的元素就能存下来

    而一个中文字符(24比特)需要3个byte数组的元素才能存下来

    看下面这个例子:

    1. public class test2
    2. {
    3. public static void main(String[] args)
    4. {
    5. String str="test a,中国,% @";
    6. //t:116 e:101 s:115 t:116 空格32 逗号:44 % 37 @ 64
    7. //汉字比较特殊一些:需要16比特来存储,也就是需要两个字节来存储
    8. //中:-28 -72 -83 国:-27 -101 -67 中文逗号:-17 -68 -116
    9. byte[] bytes=str.getBytes();
    10. for(int b:bytes)
    11. {
    12. System.out.println(b);
    13. //得到:116 101 115 116 32 97 44 -28 -72 -83 -27 -101 -67 -17 -68 -116 37 32 64
    14. }
    15. }
    16. }}

    附上ASCII表

    1. //输入一串字符(包括汉字,数字,空格,英文字母.....)分别统计出各类的个数
    2. public class test
    3. {
    4. public static void main(String[] args) throws IOException
    5. {
    6. String string=new String("");
    7. int hanzi=0;//统计汉字的个数
    8. int zimu=0;//统计字母的个数
    9. int kongge=0;//统计空格的个数
    10. int shuzi=0;//统计数字的个数
    11. int qita=0;
    12. System.out.println("请输入一行字符:");
    13. //下面两行代码的意思是:第一行:先将字符串放到缓冲区里面
    14. // 第二行:然后将缓冲区的字符串赋给string,这样string就等于我们刚才输入的字符串
    15. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    16. string=br.readLine();
    17. byte[] bytes=string.getBytes();
    18. for(int i=0;i
    19. {
    20. //System.out.println(bytes[i]);
    21. if((bytes[i]>=65&&bytes[i]<=90)||(bytes[i]>=97&&bytes[i]<=122)) zimu++;
    22. else if(bytes[i]==32) kongge++;
    23. else if(bytes[i]>=48&&bytes[i]<=57) shuzi++;
    24. else if(bytes[i]<0) hanzi++;
    25. else qita++;
    26. }
    27. System.out.println(zimu);
    28. System.out.println(hanzi/3);
    29. System.out.println(kongge);
    30. System.out.println(shuzi);
    31. System.out.println(qita);
    32. // 最终的输入输出如下:
    33. // java真是太棒了!! wotaixihuanle 123456
    34. // 17
    35. // 5
    36. // 4
    37. // 6
    38. // 2
    39. }
    40. }

  • 相关阅读:
    剑指offer-数组总结
    面试系列 - Java常见算法(一)
    cf #832 Div.2(A-D)
    C#学习笔记(3)——类型系统、命名系统、类简介、记录
    详细介绍下路由器的LAN接口
    android 33 升级踩坑 2
    k8s手撕架构图+详解
    JVM基础知识(一)jvm内存结构
    [MyBatis] SQL动态标签,SelecKey标签
    面试官问我,Redis分布式锁如何续期?
  • 原文地址:https://blog.csdn.net/weixin_47414034/article/details/126381617