I am working on a personal project and I want to take in userinput that looks like this :
1.0+2.5+3--4
and format it to something like this :
1.0 + 2.5 + 3 - -4
so far I am using the .replace("+") to .replace(" + ") and doing that for all of the operands but the problem is it makes the user input into this:
1.0 + 2.5 + 3 - - 4
Is there a way that I can make it with the negative signs. I want to do this so I could parse the numbers into doubles and add and subtract them later on.
my code for it :
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringMan {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String check = "-a1 +a2 + a3 +-a5";
check = check.replace("--", "+");
System.out.println(check);
Pattern pattern = Pattern.compile("\\s+");
Matcher matcher = pattern.matcher(check);
boolean expr = matcher.find();
String str = matcher.replaceAll(" ");
System.out.println(str);
}
}
output is:
-a1 +a2 - a3 +-a5
-a1 +a2 - a3 +-a5
the problem is I want the output to look like this: -a1 + a2 - a3 + -a5
Start by replacing -- with +, which is mathematically equivalent. Or start by replacing -- with - -, which would keep - and 4 together.
In this specific case, you can handle
--
by just replacing them with+
:--
with+
I would recommend using regular expressions and their "group" functionality. I would actually remove all whitespace to make things easier, take it out of the equation, one less thing to deal with. And obviously I would recommend simplifying the string, replacing "--" with "+", "*+" with "*" and so on.
now you can use a regex on your cleaned up string.
now you can iterate through the string using the
match.find()
method. and then usematch.group(1)
to get the sign/operation, and usematch.group(2)
to get the number...So...
PS: code is not tested, im fairly confident of the regex, but I'm not 100% sure about the grouping brackets on the first pattern.. might need to experiment
Check this , Read both strings and integers in between operators like '*,--,-,+" We can read both integers and characters.
output
a1 a2 a7 a3 a5