prateek kalra
prateek kalra

Reputation: 64

How to switch character using regular expression in Java

I want to switch "+" to "-" and "-" to "+"

for example:+ + - + - + + to - - + - + - -

How can i do this using regular expressions
I have tried using replaceAll() function but it doesn't seem to work as both the replacements cannot take place at one time.

Upvotes: 2

Views: 444

Answers (3)

john16384
john16384

Reputation: 8044

You could first replace one of the characters for something that is not used:

s = s.replace('-', '#');
s = s.replace('+', '-');
s = s.replace('#', '+');

Upvotes: 2

Jon Taylor
Jon Taylor

Reputation: 7905

If you are using Java 8 it now supports some more functional style programming, including functions such as map. Map can be applied to a stream, in this case a stream of Ints created from the String. Map applies a function (a lambda function in this case) to each member of that stream and outputs something else:

.map(x -> x) 

would essentially do nothing as it would output what you input, the stream would remain unchanged. Applying the logic within the lambda function allows you to determine the output based on some conditions.

This converted stream is then collected back together into a string builder and then output as a String.

String str = "+-+";

String inverted = str.chars().map(x -> x == '+' ? '-' : '+')
                     .collect(StringBuilder::new,
                              StringBuilder::appendCodePoint, 
                              StringBuilder::append)
                     .toString();

// inverted now contains "-+-"

This way there is no need to change to an intermediate character and go over the string twice, you only have to look at each character once.

Upvotes: 1

Kriegel
Kriegel

Reputation: 433

One weird way to achieve this is to split at one of the characters, let's say +. Then replace all - in all resulting chunks by + and as a last step concatenate all chunks with -.

    String str = "++--+++---+-++";
    String[] split = str.split("[+]", Integer.MAX_VALUE);
    String[] chunks = new String[split.length];
    for (int i = 0, l = split.length; i<l; i++) {
        chunks[i] = split[i].replaceAll("-", "+");
    }
    String result = String.join("-", chunks);

Upvotes: 1

Related Questions