根据给定的字节数,截取字符串

  今天遇到这样一题目:有一字符串,例如“abc中国”,如果要求截取4个字节,则输出“abc”,如果截取5个字节,输出“abc中”,现输入一个任意的字符串和字节数,要求输出截取后的字符串。我写的代码如下:

 

 import java.util.Scanner;

public class StringTruncate
{
 /**
 * @auther badu  2009-11-7
 * @purpose 按字节数截取字符串
 */
 public static void main(String [] args)
 {
  Scanner in =new Scanner(System.in);
  String str="";
  StringBuffer bStr=new StringBuffer();
  int num=0;
  //标记输入字符串的下标
  int j=0;
  System.out.print("Please input your string: ");
  str=in.nextLine();
  System.out.print("Please input the byte num: ");
  num=in.nextInt();

        System.out.println("str: "+str);
        System.out.println("num: "+num);

        for(int i=0;i<num;)
        {
   //getBytes()方法总是提示无法消除引用,不知道如何解决
   //if(str.charAt(i).getBytes()>1)

   //截取汉字字符
   //中文字符的unicode编码区间为【0x4e00-0x9fee】
   if(str.charAt(j)>=0x4e00&&str.charAt(j)<=0x9fbb)
   {
    //截取汉字时,往后移一位,如果不超过字节数,截取
    if(++i<num)
    {
     bStr.append(str.charAt(j));
     i++;
     j++;
    }
    //否则,结束循环
    else
       break;
   }
   //截取非汉字字符
   else
   {
    bStr.append(str.charAt(j));
    i++;
    j++;
   }
  }

  System.out.println("truncate string is :"+bStr.toString());

 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值