Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将包含%2b的字符串替换为+;使用Java?_Java_Utf 8 - Fatal编程技术网

如何将包含%2b的字符串替换为+;使用Java?

如何将包含%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

我有一个字符串“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.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