繁体   English   中英

如何从字符串 url 中删除特定的字符串

[英]How to remove particular String from String url

我必须删除它。

String removeKey = "problem_keys";

代码

public class Solution {
    
public static void main(String args[]) {
    
        String removeKey = "problem_keys";
        String url = "{\"arrival_mode:Self Drop;schedule:2020-09-10;payment_mode:Pay Online;address_id:67052;problem_id:11;problem_name:Abnormal noise;first:2000;product_name:demo tc;category_name:selfby;brand_name:bpl;transaction_type:Request;type:Display;problem_keys:1,35,3,4,5,6,7,15,16,11,12,16;\";}";
        StringBuffer sb = new StringBuffer(url);
        removeKey(sb, removeKey);
        System.out.println(sb.toString());
    }

    public static void removeKey(StringBuffer url, String removeKey) {
        int sIndex = url.indexOf(removeKey);
        while (url.charAt(sIndex) != ';') {
            url.deleteCharAt(sIndex);
        }
        url.deleteCharAt(sIndex);
    }
}

预期输出。

{"arrival_mode:Self Drop;schedule:2020-09-10;payment_mode:Pay Online;address_id:67052;problem_id:11;problem_name:Abnormal noise;first:2000;product_name:demo tc;category_name:selfby;brand_name:bpl;transaction_type:Request;type:Display;}";

猜测您还想使用 java 8 删除“值”:

 String toRemove = Arrays.stream(url.split(";")).filter(part -> part.contains(removeKey)).findFirst().orElse("");
 String newUrl = url.replace(toRemove, "");
 System.out.println(newUrl);

说到分隔符,您可以考虑添加“;” 到条件块中的 toRemove 字符串。

如果您的目标只是摆脱字符串 removeKey,您可以:

url.replace(removeKey, "");

我会这样做:

String removeKey = "problem_keys;";
url = url.replace(removeKey, "") // Replace the whole "problem_keys;" string with an empty string

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM