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?

BVtp
  • 2,308
  • 2
  • 29
  • 68

2 Answers2

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.

Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
  • Thanks. Do you think there is a solution via 'Pattern's, perhaps, for this task? – BVtp Apr 12 '16 at 08:09
  • 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 – Draken Apr 12 '16 at 08:16
  • 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? – BVtp Apr 12 '16 at 08:24
  • The above function would do that task for you. – Prerak Sola Apr 12 '16 at 08:27
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
Nicola Uetz
  • 848
  • 1
  • 7
  • 25
  • 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. – BVtp Apr 12 '16 at 08:03
  • ah sorry... Yeah sure... but I don't know how it would work in your case. Use replaceAll("[A-Za-z]", "") – Nicola Uetz Apr 12 '16 at 08:05
  • 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. – JammuPapa Apr 12 '16 at 08:13