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?
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?
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);
}
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 ");
Matcher.appendReplacement() for full description.