分享

一个字符串处理的算法

 高山流水1990 2011-10-25

问一个关于字符串处理的算法

悬赏:3 发布时间:2011-03-08 提问人:xiaqi1210 (初级程序员)

写一个方法,要求按照指定的字节数来截取字符串,注意:如果最后截取的是半个汉字的话,就舍去

如:"abc是123",截取4个字节,结果是"abc",截取5个字节,结果是"abc是"

采纳的答案

2011-03-09 enet_java (架构师)

引用

public void subString(String str,int ind){  
          
        byte[] bs = str.getBytes();  
          
        String result = "";  
          
        int count = 0;  
          
        if(str.length() > 0 && ind != 0 ){  
            //计数器  
            for(int i = 0 ; i <= ind - 1;i++){  
                if(bs[i]<0) {  
                    count++;  
                }  
            }  
            System.out.println("count: " + count);  
              
            //截取一般汉字时必定为奇数,并且为负数。截取字符前进一。  
            if(bs[ind] < 0 && (count%2) != 0 ){  
                String temp = new String( bs,0,ind-1);  
                System.out.println("截取后的:" + temp);  
            }else{  
                String temp = new String( bs,0,ind);  
                System.out.println("正好不用截取的:" + temp);  
            }  
        } 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多