Reputation: 6242
I have a PHP script <?=str_replace(array('(',')','-',' ','.'), "", $rs["hq_tel"])?>
this is a string replace function that take array of chars and replace them if find any of the char in string. Is there any java equivalent of the function. I found some ways but some are using loop and some repeating the statements but not found any single line solution like this in java.
Thanks in advance.
Upvotes: 12
Views: 89245
Reputation: 2434
If you don't know about regex you can use something more elaborated:
private static ArrayList<Character> special = new ArrayList<Character>(Arrays.asList('(', ')', '-', ' ', '.'));
public static void main(String[] args) {
String test = "Hello(how-are.you ?";
String outputText = "";
for (int i = 0; i < test.length(); i++) {
Character c = new Character(test.charAt(i));
if (!special.contains(c))
outputText += c;
else
outputText += "";
}
System.out.println(outputText);
}
Output: Hellohowareyou?
EDIT (without loop but with regex):
public static void main(String[] args) {
String test = "Hello(how-are.you ?)";
String outputText = test.replaceAll("[()-. ]+", "");
System.out.println(outputText);
}
Upvotes: 3
Reputation: 2006
your solution is here..
Replace all special character
str.replaceAll("[^\\dA-Za-z ]", "");
Replace specific special character
str.replaceAll("[()?:!.,;{}]+", " ");
Upvotes: 21
Reputation: 45090
You can use a regex like this:
//char1, char2 will be replaced by the replacement String. You can add more characters if you want!
String.replaceAll("[char1char2]", "replacement");
where the first parameter is the regex
and the second parameter is the replacement
.
Refer the docs on how to escape special characters(in case you need to!).
Upvotes: 31