java去全半角空格,trim(), replaceAll(" +",""),replaceAll("\\s*", ""), replaceAll(" | ", "")

时间:2022-06-03 07:51:12
JAVA中去掉空格  

. String.trim()
trim()是去掉首尾空格 

.str.replace(" ", ""); 去掉所有空格,包括首尾、中间
String str = " hell o ";
String str2 = str.replaceAll(" ", "");
System.out.println(str2); 

.或者replaceAll(" +",""); 去掉所有空格 

.str = .replaceAll("\\s*", "");
可以替换大部分空白字符, 不限于空格
\s 可以匹配空格、制表符、换页符等空白字符的其中任意一个 

java去掉全角空格和半角空格的方法,
需求1:将字符串转换成字符数组
String value = "  俞子东 ";
        char[] val = new char[value.length()];
        value.getChars(, value.length(), val, );//字符串转换成字符数组
        System.out.println(val.length)

需求2:将所有的全角空格和半角空格去掉
System.out.println(value.replaceAll(" | ", ""));

需求3:将字符串两边的半角空格、全角空格去掉(调用myTrim(value, "  ");)
static String myTrim(String source, String toTrim) {//将字符串两边的半角空格、全角空格去掉,其他也可以
        StringBuffer sb = new StringBuffer(source);
        )).toString()) != -) {
            sb.deleteCharAt();
        }
        ))
                .toString()) != -) {
            sb.deleteCharAt(sb.length() - );
        }
        return sb.toString();
    }

完整代码:
package com.konglong.test;
public class TrimTest {
    public static void main(String[] args) {
        String value = "  俞子东 ";
        char[] val = new char[value.length()];
        value.getChars(, value.length(), val, );//字符串转换成字符数组
        System.out.println(val.length);
        System.out.println(value.replaceAll(" | ", ""));
        System.out.println(myTrim(value, "  "));
    }
    static String myTrim(String source, String toTrim) {//将字符串两边的半角空格、全角空格去掉,其他也可以
        StringBuffer sb = new StringBuffer(source);
        )).toString()) != -) {
            sb.deleteCharAt();
        }
        ))
                .toString()) != -) {
            sb.deleteCharAt(sb.length() - );
        }
        return sb.toString();
    }
}