A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© simonqian 中级黑马   /  2013-5-11 10:43  /  1232 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 simonqian 于 2013-5-11 19:57 编辑

编写一个程序,输入字节和字符,输出按字节的长度截取字符串?保证汉字不被截取

评分

参与人数 1技术分 +1 收起 理由
HM汪磊 + 1

查看全部评分

2 个回复

倒序浏览
  1. public class CutString {

  2. /**
  3.   * @param input
  4.   *            输入字符串
  5.   * @param subLength
  6.   *            想要截取的字节数
  7.   * @throws UnsupportedEncodingException
  8.   */
  9.        
  10. public String subStrByBytes(String input, int subLength)
  11.         throws UnsupportedEncodingException {
  12.         // 总的字符数,A是一个字符,汉字也只是一个字符
  13.         int totalCharacter = input.length();
  14.         // 总的字节数
  15.         int totalBytes = input.getBytes("GBK").length;
  16.        
  17.         System.out.println("字符串\"" + input + "\"的总字节数是: " +
  18.                         input.getBytes("GBK").length + "\n" + "总字符数是: " +
  19.                         totalCharacter);
  20.         if(subLength > totalBytes){
  21.                 System.err.println("输入长度错误!请重新输入。");
  22.                 return "";
  23.         }
  24.        
  25.         int current = 0;
  26.         String result = "";
  27.        
  28.         // 遍历字符串,直到截取目标长度
  29.         for (int i = 0; i < totalCharacter; i++) {
  30.                 String tmp = input.substring(i, i + 1);
  31.                 int c_len = tmp.getBytes("GBK").length;
  32.                 if (current < subLength) {
  33.                         current += c_len;
  34.                         result += tmp;
  35.                 }
  36.         }
  37.         System.out.println("截取" + subLength + "个字节后的结果是: " + result + "\n");

  38.         return result;
  39. }

  40. public static void main(String[] args) throws UnsupportedEncodingException {
  41.         String str1 = "我ABC";
  42.         int len1 = 4;
  43.         String str2 = "我ABC汉DEF";
  44.         int len2 = 6;
  45.        
  46.         Test10 demo1 = new Test10();
  47.         //打印字符串我"我ABC"截取4个字节的结果
  48.         String out1 = demo1.subStrByBytes(str1, len1);
  49.        
  50.         Test10 demo2 = new Test10();
  51.         //打印字符串我"我ABC汉DEF"截取6个字节的结果
  52.         String out2 = demo2.subStrByBytes(str2, len2);
  53.        
  54.         }
  55. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
HM汪磊 + 1

查看全部评分

回复 使用道具 举报
好难。我才入门 怎么什么都看不懂
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马