2

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.

3 Answers 3

2

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

s = s.replace('-', '#');
s = s.replace('+', '-');
s = s.replace('#', '+');
Sign up to request clarification or add additional context in comments.

3 Comments

good idea, you have a small thing you should to change it + with \\+ or you can use replace instead of replaceAll like this s.replace("-", "#").replace("+", "-").replace("#", "+") ;)
As pointed out by a previous comment replaceAll takes a regex as its first argument, for this reason the code provided will not work. Instead the + should be replaced with a \\+ in order to escape both in Java and Regex and search for an actual +.
@YCF_L More than happy to remove as it's now changed. Rushing to answers though means we end up with crap all over SO that doesn't even work because people want to be first to answer. Will continue down voting incorrect answers.
1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.