`
115893520
  • 浏览: 140567 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

一道面试题

阅读更多

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

package com.test;

public class SplitString
{
   public void split(String s,int len)
{
       String result="";
       int counter=0;
       int i=0;
       char temp;
       while(counter<len)
    {
    	  if(i>=s.length()){
    		  break;
    	  }
           temp=s.charAt(i);
           if(Character.getNumericValue(temp)!=-1)
         {
              result=result+temp;
              counter++;
              i++;
           }
           else
        {
              result=result+temp;
              counter=counter+2;
              i++;
           }
         }
        if(counter>len)                //去掉多出的半个中文字节
     {
           if(len==1)
        {
             result="";
           }
           else{
          result=result.substring(0,i-1);
          }
        }
       System.out.println(result);
   }
   
   public SplitString()
  {}
   
   public static void main(String[] args)
{
      SplitString test=new SplitString();
      String a="我A掉多出BC汉DEF";
      test.split(a,50);
   }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics