写一个函数,2 个参数,1 个字符串,1 个字节数,返回截取的字符串,要 求字符串中的中文不能出现乱码

来源:互联网 发布:网络识别不了怎么办 编辑:程序博客网 时间:2024/06/01 07:54


写一个函数,2 个参数,1 个字符串,1 个字节数,返回截取的字符串,要

求字符串中的中文不能出现乱码:如(“我 ABC”,4)应 该 截 为“我 AB”,输 入(“我

ABC 汉 DEF”,6)应该输出为“我 ABC”而不是“我 ABC+汉的半个”。

<span style="font-size:18px;">package com.test;public class test {      public static String subString(String str, int subBytes) {     int bytes = 0; // 用来存储字符串的总字节数     for (int i = 0; i < str.length(); i++) {     if (bytes == subBytes) {      return str.substring(0, i);     }    char c = str.charAt(i);     if (c < 256) {       bytes += 1; // 英文字符的字节数看作 1   }      else {      bytes += 2; // 中文字符的字节数看作 2    if(bytes - subBytes == 1){    return str.substring(0, i);          }        }    }return str;}    public static void main(String[] args) {        String s="大家好!现在输入abcdefg,ok,完了";        System.out.println(subString(s, 10));    }   }</span>
输出结果:大家好!现

可见,一个汉字占两个字节。一个标点符号也是2个字节。

0 0