yyyyyyyyyyyyyyyyyyyy

博客园 首页 新随笔 联系 订阅 管理
JAVA中去掉空格  
 
1. String.trim() 
trim()是去掉首尾空格 
 
2.str.replace(" ", ""); 去掉所有空格,包括首尾、中间 
String str = " hell o "; 
String str2 = str.replaceAll(" ", ""); 
System.out.println(str2); 

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

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


java去掉全角空格和半角空格的方法,
需求1:将字符串转换成字符数组
String value = "  俞子东 ";
        char[] val = new char[value.length()];
        value.getChars(0, value.length(), val, 0);//字符串转换成字符数组
        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);
        while (toTrim.indexOf(new Character(sb.charAt(0)).toString()) != -1) {
            sb.deleteCharAt(0);
        }
        while (toTrim.indexOf(new Character(sb.charAt(sb.length() - 1))
                .toString()) != -1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        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(0, value.length(), val, 0);//字符串转换成字符数组
        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);
        while (toTrim.indexOf(new Character(sb.charAt(0)).toString()) != -1) {
            sb.deleteCharAt(0);
        }
        while (toTrim.indexOf(new Character(sb.charAt(sb.length() - 1))
                .toString()) != -1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}

 

 

posted on 2015-12-01 00:03  xxxxxxxx1x2xxxxxxx  阅读(1772)  评论(0编辑  收藏  举报