去掉全角空格和半角空格


需求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:將所有的全角空格和半角空格去掉

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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM