1. 程式人生 > >替換空格(空白字元)詳解

替換空格(空白字元)詳解

替換空格(空白字元)詳解

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexpTest {
    private static String str2;
    /*
     * [\\s|/u3000]
     * \s 空白字元 包括 
     * \t   tab鍵  製表符
     * \n   換行符
     * \r   回車符
     * \f   換頁符
     * 
     * \u3000 全形空格
     */
    public static
String replaceBlank(String str) { String result = null; str2 = str; if("".equals(str2) || str2 == null) return result; Pattern pattern = Pattern.compile("[\\s|\u3000]+"); Matcher matcher = pattern.matcher(str); result = matcher.replaceAll("%20"
); return result; } public static void main(String[] args) { String result = null; String source = "我愛 中國,我 愛 北 京"; result = replaceBlank(source); System.out.println(result); } }

輸出:
我愛%20中國,我%20愛%20北%20京