Er.Prem Singh daksha
Er.Prem Singh daksha

Reputation: 393

How to remove particular String from String url

I have to remove this.

String removeKey = "problem_keys";

Code

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);
    }
}

Expected output.

{"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;}";

Upvotes: 0

Views: 109

Answers (2)

Esotopo21
Esotopo21

Reputation: 412

Guessing you want also to remove the "values", using java 8:

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

Speaking about the delimeters you can consider adding ";" to the toRemove string in a conditional block.

If you're aim is only to get rid of the string removeKey you can just:

url.replace(removeKey, "");

Upvotes: 1

Renis1235
Renis1235

Reputation: 4700

I would go with this:

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

Upvotes: 0

Related Questions