Which would be a better approach (time and space) for removing characters from a String:
Approach 1:
String charsToRemove = "abc";
String myString = "abcdef";
myString = myString.replaceAll("["+charsToRemove+"]", "");
Approach 2:
// Initialized to charsToRemove
HashSet<Character> charsToRemoveSet = ...
Character[] myCharArray = myString.toCharArray();
int dst = 0;
for(int src=0; src<myCharArray.length; src++) {
if(!charsToRemoveSet.contains(myCharArray[src]))
myCharArray[dst++] = myCharArray[src];
}
myString = new String(myCharArray, 0, dst);
Visually, option 1 is much clearer. This alone is enough to make me choose it. It’s also probably faster, as well (though it depends on the lengths of your input). In option two, you’re setting up a second loop.
HashSet.contains()runs its own loop, adding a second delay.For short strings, you likely won’t notice a difference, but once again, it’s hard to tell what’s happening in the second.