package com.jingsong.bug;
/**
* @author jingsong
* @date 2022/5/26 23:46
* @desc 简述一个空格引起的bug,bug不难解决,但是比较费眼睛
* 主要原因是ASCII码表中32号和130号都是空格,不容易发现
*/
public class SpaceBug {
public static void main(String[] args) {
// 项目中需要解析一个字符串,去除空格后再进行操作
char[] chars1 = new char[]{'h', 'e', 32, 'l', 'l', 32, 'o'};
String s1 = new String(chars1);
// 一般可以使用replaceAll方法去除空格
System.out.println(s1);
System.out.println(s1.replaceAll(" ", ""));
// 但是
System.out.println();
// 我接收到的空格比较顽固,去除不掉(这个空格更长)
char[] chars2 = new char[]{'h', 'e', 32, 'l', 'l', 130, 'o'};
String s2 = new String(chars2);
System.out.println(s2);
System.out.println(s2.replaceAll(" ", ""));
// 于是
System.out.println();
// 自己编写一个工具类,去除空格
String s3 = forceTrim(s2);
System.out.println(s3);
}
public static String forceTrim(String target) {
char[] chars = target.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 32 || chars[i] == 130) {
continue;
}
sb.append(chars[i]);
}
return sb.toString();
}
}
bug004_一个空格引起的bug
最新推荐文章于 2025-06-21 10:41:56 发布