如何将包含%2b的字符串替换为+;使用Java?
我有一个字符串“demo%2buser”。我需要将“%2b”转换为“+”。i、 演示+用户。您可以使用如何将包含%2b的字符串替换为+;使用Java?,java,utf-8,Java,Utf 8,我有一个字符串“demo%2buser”。我需要将“%2b”转换为“+”。i、 演示+用户。您可以使用replaceAll()方法 String input = "demo%2buser"; input = input.replaceAll("%2b","+"); System.out.println(input); 只需像这样执行String::replace()- String s = "demo%2buser"; s = s.replace("%2b", "+"); 看看类java.n
replaceAll()
方法
String input = "demo%2buser";
input = input.replaceAll("%2b","+");
System.out.println(input);
只需像这样执行
String::replace()
-
String s = "demo%2buser";
s = s.replace("%2b", "+");
看看类
java.net.URLDecoder
;它为您提供了适当的功能。通常,我会在URL中看到这些%2b
和其他%
相关值。因此,搜索URL解码器时,以下内容应该会有所帮助
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
public class Main
{
public static String decodeValue(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex.getCause());
}
}
public static void main(String[] args) {
String encodedValue = "demo%2buser";
// Decoding the URL encoded string
String decodedValue = decodeValue(encodedValue);
System.out.println(decodedValue);
}
}
输出:
demo+user