首页 技术 正文
技术 2022年11月19日
0 收藏 624 点赞 3,984 浏览 943 个字

编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4

  1. public class StringSplit {
  2. public static void main(String[] args) throws Exception {
  3. String ss = “a很bc你好”;
  4. System.out.println(splitString(ss, 1));
  5. }
  6. public static String splitString(String str, int byteLength)
  7. throws Exception {
  8. //如果字符串为空,直接返回
  9. if(str == null || “”.equals(str)) {
  10. return str;
  11. }
  12. //用于统计这个字符串中有几个中文字符
  13. int wordCount = 0;
  14. //统一按照gbk编码来得到他的字节数组,因为不同的编码字节数组是不一样的。
  15. byte[] strBytes = str.getBytes(“GBK”);
  16. //如果只截取一位,而且第一位是中文字符时的处理
  17. if (byteLength == 1) {
  18. if (strBytes[0] < 0) {
  19. return str.substring(0, 1);
  20. }
  21. }
  22. //字符串中的一个中文会使得wordCount 加两次
  23. //如果你这个字节取出来的是一个汉字也就是两个字节当中的一个的话val的值为负数
  24. for (int i = 0; i < byteLength; i++) {
  25. int val = strBytes[i];
  26. if (val < 0) {
  27. wordCount++;
  28. }
  29. }
  30. //如果传递的这个截取的位数没有截到半个中文上面,那么就按照byteLength – (wordCount / 2个长度进行截取
  31. if (wordCount % 2 == 0) {
  32. return str.substring(0, (byteLength – (wordCount / 2)));
  33. }
  34. //否则,我们就舍弃多出来的这一位 所以  -1
  35. return str.substring(0, (byteLength – (wordCount / 2) – 1));
  36. }
  37. }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,086
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,561
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,410
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,183
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,820
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,903