判断一个字符串是不是乱码

/**  
         *  用getBytes(encoding):返回字符串的一个byte数组  
         *  当b[0]为  63时,应该是转码错误  
         *  A、不乱码的汉字字符串:  
         *  1、encoding用GB2312时,每byte是负数;  
         *  2、encoding用ISO8859_1时,b[i]全是63。  
         *  B、乱码的汉字字符串:  
         *  1、encoding用ISO8859_1时,每byte也是负数;  
         *  2、encoding用GB2312时,b[i]大部分是63。  
         *  C、英文字符串  
         *  1、encoding用ISO8859_1和GB2312时,每byte都大于0;  
         *  <p/>  
         *  总结:给定一个字符串,用getBytes("iso8859_1")  
         *  1、如果b[i]有63,不用转码;  A-2  
         *  2、如果b[i]全大于0,那么为英文字符串,不用转码;  B-1  
         *  3、如果b[i]有小于0的,那么已经乱码,要转码。  C-1  
         */  
       private  static  String  toGb2312(String  str)  {  
               if  (str  ==  null)  return  null;  
               String  retStr  =  str;  
               byte  b[];  
               try  {  
                       b  =  str.getBytes("ISO8859_1");  
 
                       for  (int  i  =  0;  i  <  b.length;  i++)  {  
                               byte  b1  =  b[i];  
                               if  (b1  ==  63)  
                                       break;    //1  
                               else  if  (b1  >  0)  
                                       continue;//2  
                               else  if  (b1  <  0)  {        //不可能为0,0为字符串结束符  
                                       retStr  =  new  String(b,  "GB2312");  
                                       break;  
                               }  
                       }  
               }  catch  (UnsupportedEncodingException  e)  {  
                       //  e.printStackTrace();    //To  change  body  of  catch  statement  use  File    |  Settings    |  File  Templates.  
               }  
               return  retStr;  
       }  
---------------------------------------------------------------  
 
String  str  =  "";  
if  (request.getParameter("input")  !=  null)  {  
   str  =  request.getParameter("input");  
   if  (str.length()  ==  str.getBytes().length)  
       System.out.println("半角  character");  
   else  
       System.out.println("全角  character");  
}

在这里要特别感谢提供此解决方法的人,在此借用与大家分享

### 在 Java 中判断字符串是否乱码的解决方案 在 Java 中,判断字符串是否乱码可以通过多种方式实现。以下是几种常见的方法: #### 1. 使用 `Charset` 类检测编码合法性 Java 提供了 `java.nio.charset.Charset` 类来检测字符串是否可以被某种字符集正确编码。如果字符串无法被指定字符集编码,则可能为乱码。 ```java import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class CharsetValidator { public static boolean isValidEncoding(String input, String charsetName) { Charset charset = Charset.forName(charsetName); return charset.newEncoder().canEncode(input); // 判断字符串是否可以被指定字符集编码 } public static void main(String[] args) { String testString = "测试"; System.out.println(isValidEncoding(testString, "GBK")); // 输出 true 或 false[^1] } } ``` 此方法通过 `canEncode` 方法检查字符串是否符合指定字符集的规则。如果返回 `false`,则表示字符串可能是乱码。 #### 2. 检测非法字符范围 通过遍历字符串中的每个字符,检查其 Unicode 编码是否超出合法范围。如果发现任何非法字符,则认为字符串可能为乱码。 ```java public class InvalidCharacterDetector { public static boolean containsInvalidCharacters(String input) { for (char c : input.toCharArray()) { if (!Character.isValidCodePoint(c)) { // 检查字符是否为合法的 Unicode 点 return true; } } return false; } public static void main(String[] args) { String testString = "测试"; System.out.println(containsInvalidCharacters(testString)); // 输出 true 或 false } } ``` 这种方法适用于检测字符串是否存在非法字符,但可能无法完全覆盖所有乱码情况。 #### 3. 使用正则表达式匹配合法字符 通过正则表达式定义合法字符集,并验证字符串是否完全由这些字符组成。如果字符串包含未定义的字符,则认为是乱码。 ```java public class RegexValidator { public static boolean isValidByRegex(String input, String regex) { return input.matches(regex); // 检查字符串是否完全匹配正则表达式 } public static void main(String[] args) { String testString = "测试"; String regex = "[\\u4e00-\\u9fa5a-zA-Z0-9\\s]+"; // 定义合法字符集:中文、英文、数字和空格 System.out.println(isValidByRegex(testString, regex)); // 输出 true 或 false } } ``` 此方法通过正则表达式限定字符串内容,适合用于特定场景下的乱码检测[^2]。 #### 4. 自动检测编码并验证 使用第三方库(如 `juniversalchardet` 或 `icu4j`)自动检测字符串的编码,并尝试解码以验证其合法性。 ```java import org.mozilla.universalchardet.UniversalDetector; import java.io.ByteArrayInputStream; public class EncodingDetector { public static String detectEncoding(byte[] input) { UniversalDetector detector = new UniversalDetector(null); detector.handleData(input, 0, input.length); detector.dataEnd(); return detector.getDetectedCharset(); // 返回检测到的编码 } public static boolean isGarbled(String input) { byte[] bytes = input.getBytes(); String detectedCharset = detectEncoding(bytes); if (detectedCharset == null) { return true; // 如果无法检测到编码,则认为是乱码 } try { String decoded = new String(bytes, detectedCharset); return !decoded.equals(input); // 如果解码后的内容与原字符串不一致,则认为是乱码 } catch (Exception e) { return true; // 解码失败时认为是乱码 } } public static void main(String[] args) { String testString = "测试"; System.out.println(isGarbled(testString)); // 输出 true 或 false } } ``` 此方法结合自动编码检测和解码验证,能够更全面地判断字符串是否乱码[^3]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值