去掉全角空格和半角空格

需求1:將字符串轉換成字符數組數組

1 String value = "  俞子東 ";
2         char[] val = new char[value.length()];
3         value.getChars(0, value.length(), val, 0);//字符串轉換成字符數組
4 
5         System.out.println(val.length)

需求2:將全部的全角空格和半角空格去掉spa

1 System.out.println(value.replaceAll(" | ", ""));

需求3:將字符串兩邊的半角空格、全角空格去掉(調用myTrim(value, "  ");)code

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();
    }

 

完整代碼:blog

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 = null;
        if (source != null) {
            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 == null ? "" : sb.toString();
    }
}
相關文章
相關標籤/搜索