2017-08-08 158 views
1

我必須用%20來替換字符串中的所有空格。用%20替換空格

我嘗試使用方法replaceAll在此模式下title.replaceAll(" ", "%20");(顯然的標題是一個字符串),但這並不工作,結果是初始字符串中的所有空白

+2

你做捕捉新的字符串到另一個變量,對不對? (很難說,因爲你沒有提供足夠的代碼來說......) – AntonH

+6

字符串在Java中是不可變的。嘗試'字符串替換= title.replaceAll(「」,「%20」);' – janos

+1

另請參閱:https://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical -outpu – NullUserException

回答

1

解決方案

不要使用替換,我發現它沒有按預期工作。只是String.replace,並應該完成工作就好了。

public static void main (String [] args) { 

    String test = "H E L L O"; 

    test = test.replace(" ", "%20"); 
    System.out.println (test); 

} 

結果

H%20E%20L%20L%20O