0

In java is there a way to replace specific special characters with another special characters within entire text without using if else .

Eg:

String s = abcd&c!&%^ .

Replace & with ~

Replace ! with ¬ etc on the above example string.

2

2 Answers 2

1

String has a replace function, so you can do s = s.replace('&','~');

public String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.

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

4 Comments

This works for one special character replacement.How about scanning through whole content in the string and replace each special character with another special character based on condition if special character A present then replace with B.If C present then replace with D ...?
just call replace multiple times like this: s = s.replace('A','B').replace('C','D');
Condition check?Only replace if specific character is present. If 50 characters to replace I don't want to use 50 if statements.
Why do you need if statements? when you do this s = s.replace('A','B'); if there is no 'A' in your String, nothing is going to get replaced. s will stay the same.
1
String.replace​(char oldChar, char newChar);

All things you can do with String: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html

I recommend reading these docs when you're working with anything Java you don't know. Like Arrays, or Lists, and so on.

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.