您的位置:首页 > 编程语言 > Java开发

java按字节截取带有汉字的字符串的解法

2015-02-07 23:55 387 查看
本文转载地址:http://blog.csdn.net/cuker919/article/details/17281691

由于接口使用的oracle字段长度为固定字节数,然后传进来的字符串估计比数据库字段的总字节数要大,那么截取小于数据库字节数的字符串。

自己参考网上的例子,整了个递归调用就可以了,因为截取的字符字节长度必须小与数据库的字节长度,即如果最后一个字符为汉字,那么只能去掉往前截取。

    /**  

     * 判断传进来的字符串,是否  

     * 大于指定的字节,如果大于递归调用

     * 直到小于指定字节数 ,一定要指定字符编码,因为各个系统字符编码都不一样,字节数也不一样 

     * @param s  

     *            原始字符串  

     * @param num  

     *            传进来指定字节数  

     * @return String 截取后的字符串  

     * @throws UnsupportedEncodingException 

     */ 

    public static String idgui(String s,int num)throws Exception{

        int changdu = s.getBytes(
"UTF-8"
).length;

        if(changdu > num){

            s = s.substring(0, s.length() - 1);

            s = idgui(s,num);

        }

        return s;

    }
http://blog.csdn.net/yangyan19870319/article/details/6144131
java面试题:

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

目前很多流行的语言,如C#、Java内部采用的都是 Unicode 16(UCS2)编码,在这种编码中所有的字符都是两个字符,因此,如果要截取的字符串是中、英文、数字混合的,就会产生问题,如下面的字符串:

  String s = "a加b等于c,如果a等1、b等于2,那么c等3"; 

  上面的字符串既有汉字,又有英文字符和数字。如果要截取前6个字节的字符,应该是”a加b等",但如果用substring方法截取前6个字符就成了"a 加b等于c"。产生这个问题的原因是将substring方法将双字节的汉字当成一个字节的字符(UCS2字符)处理了。

 

英文字母和中文汉字在不同的编码格式下,所占用的字节数也是不同的,我们可以通过下面的例子来看看在一些常见的编码格式下,一个英文字母和一个中文汉字分别占用多少字节。

Java代码 



import java.io.UnsupportedEncodingException;
  

  

public class EncodeTest {
  

    /**  

     * 打印字符串在指定编码下的字节数和编码名称到控制台 

     *   

     * @param s  

     *            字符串 

     * @param encodingName 

     *            编码格式 

     */  

    public static void printByteLength(String s, String encodingName) {
  

        System.out.print("字节数:");
  

        try {
  

            System.out.print(s.getBytes(encodingName).length);   

        } catch (UnsupportedEncodingException e) {
  

            e.printStackTrace();   

        }   

        System.out.println(";编码:" + encodingName);
  

    }   

  

    public static void main(String[] args) {
  

        String en = "A";
  

        String ch = "人";
  

  

        // 计算一个英文字母在各种编码下的字节数  

        System.out.println("英文字母:" + en);
  

        EncodeTest.printByteLength(en, "GB2312");
  

        EncodeTest.printByteLength(en, "GBK");
  

        EncodeTest.printByteLength(en, "GB18030");
  

        EncodeTest.printByteLength(en, "ISO-8859-1");
  

        EncodeTest.printByteLength(en, "UTF-8");
  

        EncodeTest.printByteLength(en, "UTF-16");
  

        EncodeTest.printByteLength(en, "UTF-16BE");
  

        EncodeTest.printByteLength(en, "UTF-16LE");
  

  

        System.out.println();   

  

        // 计算一个中文汉字在各种编码下的字节数  

        System.out.println("中文汉字:" + ch);
  

        EncodeTest.printByteLength(ch, "GB2312");
  

        EncodeTest.printByteLength(ch, "GBK");
  

        EncodeTest.printByteLength(ch, "GB18030");
  

        EncodeTest.printByteLength(ch, "ISO-8859-1");
  

        EncodeTest.printByteLength(ch, "UTF-8");
  

        EncodeTest.printByteLength(ch, "UTF-16");
  

        EncodeTest.printByteLength(ch, "UTF-16BE");
  

        EncodeTest.printByteLength(ch, "UTF-16LE");
  

    }   

}  

运行结果如下:
英文字母:A
字节数:1;编码:GB2312
字节数:1;编码:GBK
字节数:1;编码:GB18030
字节数:1;编码:ISO-8859-1
字节数:1;编码:UTF-8
字节数:4;编码:UTF-16
字节数:2;编码:UTF-16BE
字节数:2;编码:UTF-16LE
中文汉字:人
字节数:2;编码:GB2312
字节数:2;编码:GBK
字节数:2;编码:GB18030
字节数:1;编码:ISO-8859-1
字节数:3;编码:UTF-8
字节数:4;编码:UTF-16
字节数:2;编码:UTF-16BE
字节数:2;编码:UTF-16LE

UTF-16BE和UTF-16LE是UNICODE编码家族的两个成员。UNICODE标准定义了UTF-8、UTF-16、UTF-32三种编码格式,共有UTF-8、UTF-16、UTF-16BE、UTF-16LE、UTF-32、UTF-32BE、UTF-32LE七种编码方案。JAVA所采用的编码方案是UTF-16BE。从上例的运行结果中我们可以看出,GB2312、GBK、GB18030三种编码格式都可以满足题目的要求。下面我们就以GBK编码为例来进行解答。

我们不能直接使用String类的substring(int beginIndex, int endIndex)方法,因为它是按字符截取的。'我'和'Z'都被作为一个字符来看待,length都是1。实际上我们只要能区分开中文汉字和英文字母,这个问题就迎刃而解了,而它们的区别就是,中文汉字是两个字节,英文字母是一个字节。

package com.newyulong.iptv.billing.ftpupload;

import java.io.UnsupportedEncodingException;

public class CutString {

     /** 

     * 判断是否是一个中文汉字 

     *  

     * @param c 

     *            字符 

     * @return true表示是中文汉字,false表示是英文字母 

     * @throws UnsupportedEncodingException 

     *             使用了JAVA不支持的编码格式 

     */ 

    public static boolean isChineseChar(char c)  

            throws UnsupportedEncodingException {  

        // 如果字节数大于1,是汉字  

        // 以这种方式区别英文字母和中文汉字并不是十分严谨,但在这个题目中,这样判断已经足够了  

        return String.valueOf(c).getBytes("UTF-8").length > 1;  

    }  

 

    /** 

     * 按字节截取字符串 

     *  

     * @param orignal 

     *            原始字符串 

     * @param count 

     *            截取位数 

     * @return 截取后的字符串 

     * @throws UnsupportedEncodingException 

     *             使用了JAVA不支持的编码格式 

     */ 

    public static String substring(String orignal, int count)  

            throws UnsupportedEncodingException {  

        // 原始字符不为null,也不是空字符串  

        if (orignal != null && !"".equals(orignal)) {  

            // 将原始字符串转换为GBK编码格式  

            orignal = new String(orignal.getBytes(), "UTF-8");//

          // System.out.println(orignal);

          //System.out.println(orignal.getBytes().length);

            // 要截取的字节数大于0,且小于原始字符串的字节数  

            if (count > 0 && count < orignal.getBytes("UTF-8").length) {  

                StringBuffer buff = new StringBuffer();  

                char c;  

                for (int i = 0; i < count; i++) {

                    System.out.println(count);

                    c = orignal.charAt(i);  

                    buff.append(c);  

                    if (CutString.isChineseChar(c)) {  

                        // 遇到中文汉字,截取字节总数减1  

                        --count;  

                    }  

                }  

            //   System.out.println(new String(buff.toString().getBytes("GBK"),"UTF-8"));

                return new String(buff.toString().getBytes(),"UTF-8");  

            }  

        }  

        return orignal;  

    }  

 

    /**  

     * 按字节截取字符串  

     *   

     * @param orignal  

     *            原始字符串  

     * @param count  

     *            截取位数  

     * @return 截取后的字符串  

     * @throws UnsupportedEncodingException  

     *             使用了JAVA不支持的编码格式  

     */  

    public static String gsubstring(String orignal, int count)   

            throws UnsupportedEncodingException {   

        // 原始字符不为null,也不是空字符串   

        if (orignal != null && !"".equals(orignal)) {   

            // 将原始字符串转换为GBK编码格式   

            orignal = new String(orignal.getBytes(), "GBK");   

            // 要截取的字节数大于0,且小于原始字符串的字节数   

            if (count > 0 && count < orignal.getBytes("GBK").length) {   

                StringBuffer buff = new StringBuffer();   

                char c;   

                for (int i = 0; i < count; i++) {   

                    c = orignal.charAt(i);   

                    buff.append(c);   

                    if (CutString.isChineseChar(c)) {   

                        // 遇到中文汉字,截取字节总数减1   

                        --count;   

                    }   

                }   

                return buff.toString();   

            }   

        }   

        return orignal;   

    }  

    

    /**  

     * 判断传进来的字符串,是否  

     * 大于指定的字节,如果大于递归调用

     * 直到小于指定字节数  

     * @param s  

     *            原始字符串  

     * @param num  

     *            传进来指定字节数  

     * @return String 截取后的字符串  

     */ 

    public static String idgui(String s,int num){

        int changdu = s.getBytes().length;

        if(changdu > num){

            s = s.substring(0, s.length() - 1);

            s = idgui(s,num);

        }

        return s;

    }

    

    public static void main(String[] args) throws Exception{  

        // 原始字符串  

        String s = "我ZWR爱你们JAVA";  

        System.out.println("原始字符串:" + s + " : 字节数是: " + s.getBytes().length);  

/*            System.out.println("截取前1位:" + CutString.substring(s, 1));  

            System.out.println("截取前2位:" + CutString.substring(s, 2));  

            System.out.println("截取前4位:" + CutString.substring(s, 4)); */ 

            //System.out.println("截取前12位:" + CutString.substring(s, 12));  

            System.out.println("截取前12字节:" + CutString.idgui(s, 11));  

       

    }   

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 截取字符串
相关文章推荐