Lazar K Lazar K - 1 year ago 31
Java Question

Simpler way to remove a large amount of characters from a string?

i want to remove a set of characters from a string in the most efficient way possible.

Right now i just copy and paste the one code line but there has to be a more efficient way!

My code:

ProductName = ProductName.replace("!", "");
ProductName = ProductName.replace("#", "");
ProductName = ProductName.replace("$", "");
ProductName = ProductName.replace("%", "");
ProductName = ProductName.replace("^", "");
ProductName = ProductName.replace("&", "");
ProductName = ProductName.replace("*", "");
ProductName = ProductName.replace("(", "");
ProductName = ProductName.replace(")", "");
ProductName = ProductName.replace("?", "");
ProductName = ProductName.replace("[", "");
ProductName = ProductName.replace("{", "");
ProductName = ProductName.replace("}", "");
ProductName = ProductName.replace("]", "");
ProductName = ProductName.replace("/", "");
ProductName = ProductName.replace(".", "");
ProductName = ProductName.replace("<", "");
ProductName = ProductName.replace(">", "");
ProductName = ProductName.replace(",", "");


Don't overcomplicate things. For now try to focus on way which will be easier to maintain rather than efficiency.

One way to do it could be using regex and its character class - for instance regex like [abc] represents one character which is either a b or c.

You just need to be careful here since some characters have special meaning even in character class (like - which can be used to create range of characters like a-z, or ] which simply represents end of character class).
To avoid any problems with such special characters we can create area where alll characters should be treated as literals (characters without special meaning). To create such area so we can use \Q...\E (for more info about it read last paragraph of section).

So your code could look like

String removeThese = "!#$%^&*()?[{}]/.<>,";
ProductName = ProductName.replaceAll("[\\Q"+removeThese +"\\E]", "");

Also according to Java naming convention variables should start with lowercase so your ProductName should be productName.