需要用百分号Java替换字符串中的空格

LS_*_*LS_ 0 java

我需要用%符号替换字符串中的空格,但我遇到了一些问题,我尝试的是:

imageUrl = imageUrl.replace(' ', "%20");
Run Code Online (Sandbox Code Playgroud)

但它在替换功能中给了我一个错误.

然后:

imageUrl = imageUrl.replace(' ', "%%20");
Run Code Online (Sandbox Code Playgroud)

但它仍然在替换功能中给我一个错误.

我尝试使用unicode符号:

imageUrl = imageUrl.replace(' ', (char) U+0025 + "20");
Run Code Online (Sandbox Code Playgroud)

但它仍然给出错误.

有一个简单的方法吗?

Uma*_*nth 6

String.replace(String, String) 是你想要的方法.

更换

imageUrl.replace(' ', "%");
Run Code Online (Sandbox Code Playgroud)

imageUrl.replace(" ", "%");

System.out.println("This is working".replace(" ", "%"));
Run Code Online (Sandbox Code Playgroud)

我建议你在java中使用URL Encoderfor Encoding Strings.

String searchQuery = "list of banks in the world";
String url = "http://mypage.com/pages?q=" + URLEncoder.encode(searchQuery, "UTF-8");
Run Code Online (Sandbox Code Playgroud)