问题描述:

I have added several characters in a list to replace in a string. Here they are:

List<Character> list = new ArrayList<Character>();

list.add(',');

list.add('?');

list.add(',');

list.add(':');

list.add('-');

list.add('(');

list.add(')');

list.add(';');

list.add('/');

I want to replace all occurrences of the character in the list in a string "s".

s.replaceAll(list, "");

I can't do that, of course, because list is NOT a string. But what can I do instead?

EDIT so if

String s = "I am cool; not good!";

I want the list to recognize that it contains ";" and "!", and replace those characters in the String s with nothing. So the result would be:

"I am cool not good"

网友答案:

Rather than use a List<Character>, I would use a regex:

s.replaceAll("[,?:();/-]","");

If you absolutely must define your characters in a List, convert the List to such a regex first.

网友答案:

Rather than List why not use a regular expression. Otherwise you may be stuck with something like:

StringBuilder mySB = new StringBuilder(myString);
for (Character myChar : list) {
  mySB.replace(String.valueOf(myChar), "");
}

myString = mySB.toString();
网友答案:

check out Apache Commons StringUtils.replaceEach((String text, String[] searchList, String[] replacementList)) it will allow you to provide a list of values to search for and a list of associated replacements in a single line.

Note: This will throw IndexOutOfBoundsException if the lengths of the search and replacement arrays are not the same

相关阅读:
Top