12

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.

2
  • I believe that a single line for doing this is supported out of the box in Java. However you are free to write a function that does this. Then you can use a similar way to invoke it. Thank You. Commented Jun 19, 2013 at 10:49
  • Use replaceAll on the String class giving an appropriate regex that will match any of your desired chars to replace. Commented Jun 19, 2013 at 10:51

4 Answers 4

31

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!).

Sign up to request clarification or add additional context in comments.

2 Comments

This will be a comma (,) separated list ?
@zzzz Give it a try and you'll know.
21

your solution is here..

Replace all special character

str.replaceAll("[^\\dA-Za-z ]", "");

Replace specific special character

str.replaceAll("[()?:!.,;{}]+", " ");

Comments

3

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);
}

2 Comments

but i dont want to use a loop dear.
@zzzz. Sorry, I didn't read the no loop option!. Eddited to replace only the characters you had in your array using regex like the rest of fellas commented.
2

String.replaceAll(String regex, String replacement)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.