将字符串转码

   一,知道字符串编码的情况下           

                     String s1 = "hello中国人"; 

                     String iso = new String(s1.getBytes("utf-8"), "iso-8859-1"); 
                     System.out.println(iso);//hello中国人 
                     String utf8 = new String(iso.getBytes("iso-8859-1"), "utf-8"); 
                     System.out.println(utf8);//hello中国人 

                     String s1 = "hello中国人"; 
                     String gbk = new String(s1.getBytes("utf-8"), "gbk"); 
                     System.out.println(gbk);//hello涓浗浜� 
                     String utf8 = new String(gbk.getBytes("gbk"), "utf-8"); 

                    System.out.println(utf8);//hello中国�? 

二,不知道字符串编码的情况下,先获得字符串编码,然后再转编码

       在Java中,String的getBytes()方法是得到一个操作系统默认的编码格式的字节数组。

    而与getBytes相对的,可以通过new String(byte[], decode)的方式来还原字符串,

String的getBytes()方法是得到一个系统默认的编码格式的字节数组

getBytes("utf-8") 得到一个UTF-8格式的字节数组

三,获取字符串编码:

public class test {
public  String getEncoding(String str) {
        String encode = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
           
//                String str= "hello中国人"; 
//                   // 将字符串str转成  GB2312编码格式 赋给str1    
//                String str1 = new String(str.getBytes(encode),encode);
//                   // 如果str仍然等于str1,那么就可以确定str就是 encode格式              
//                if(str.equals(str1)){
//                 return encode;
//                }
                
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
              
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        

        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        
   
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode), encode))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "";
    }
}

           

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱若手握流沙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值