0

Example:

String originalString = "This is just a string folks";

I want to remove(or replace them with "") : 1. "This is" , 2. "folks" Desired output :

finalString = "just a string";

For a sole substring it's easy, we can just use replace/replaceAll. I also know it works for various numeric values replace("[0-9]","") But can that be done for characters?

0

2 Answers 2

4

You can create a function like below:

String replaceMultiple (String baseString, String ... replaceParts) {
    for (String s : replaceParts) {
        baseString = baseString.replaceAll(s, "");
    }
    return baseString;
}

And call it like:

String finalString = replaceMultiple("This is just a string folks", "This is", "folks");

You can pass multiple strings that are to be replaced after the first parameter.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Do you think there is a solution via 'Pattern's, perhaps, for this task?
Since your pattern is a bit vague, possibly not. You could pass through regex to do this, however you need to be careful with your pattern matching
Thanks. last question, if I have the word "notbe" for example. and I want to remove all the "not" prefix , so that "notbe" would become "be". Do you have an idea how can that be achieved?
The above function would do that task for you.
0

It works like this:

String originalString = "This is just a string folks";
originalString = originalString.replace("This is", "");
originalString = originalString.replace("folks", "");
//originalString is now finalString

3 Comments

Well that solution is pretty obvious. My question Is whether there is a more efficient or more "elegant" way to do so? Cause I have many substrings to cover, and I want to be able to easily add more in the future.
ah sorry... Yeah sure... but I don't know how it would work in your case. Use replaceAll("[A-Za-z]", "")
you can always create an enum of all the substrings you want to replace and can easily add more in case you need to scale up in future.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.