2

My String input is String Number = "546+90".

I want to give output like this "546 + 90".how can i do it in java? Right now I am trying:

Number.replaceAll("[0-9]"," ");

But it doesn't seem to be working. Does anyone have any suggestions?

3
  • 2
    Don't capitalize variable names Commented Apr 6, 2016 at 18:01
  • seems there is confusion whether the input is "String Number=546+90" or just "546+90" Commented Apr 6, 2016 at 18:19
  • I've made mistake.sorry!!!. its "546+90". i have edited it. Commented Apr 6, 2016 at 18:37

3 Answers 3

2

Strings are immutable so you need to get the string resultant of the replace method:

public static void main(String[] args) {
        String number="546+90";
        number  = number.replaceAll("\\+" , " + ");

        System.out.println(number);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

isn't + reserved? maybe it needs an escape
0

First, Number is a built-in class in the java.lang package, so you should never use that name.

Second, variables should be written in lower-case, so it should be number.

Third, Strings are immutable, so the need to get the return value from replaceAll().

If you want this string: "String Number=546+90"
to become this string: "546 + 90"
then you need to strip anything before = and add spaces around the +.

This can be done by chaining replace calls:

String number = "String Number=546+90";
number = number.replaceFirst(".*=", "")
               .replaceAll("\\+", " + ");
System.out.println(number);

If you want other operators too, use a character class. You have to capture the character to retain it in the replacement string, and you must put - first or last (or escape it).

number = number.replaceFirst(".*=", "")
               .replaceAll("([-+*/%])", " $1 ");

1 Comment

So that whichever operator character is matched will be retained. See Matcher.appendReplacement() for full description.
0

Adding an escape characters will solve your problem
String Number = "\"" + "546+90" + "\"";

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.