Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace multiple items in a list?

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"
like image 846
Macosx Iam Avatar asked Jun 03 '26 16:06

Macosx Iam


1 Answers

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.

like image 95
Bohemian Avatar answered Jun 05 '26 08:06

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!