I have a class called: ComplexNumber and I have a string that I need to convert into a ComplexNumber (Using Java).
If I have: “5+3i” or “6-2i”, how do I appropriately parse these strings. I need to get it to 2 variables and I can do the rest.
String complexNum = "5+3i";
I would need to split the previous string into two double type variables
double real = 5;
double imag = 3;
String complexNum = "6-2i";
I would need to split the previous string into two double type variables
double real = 6;
double imag = -2;
Can anyone give example code as to how they would go about doing this? There aren’t any spaces to use as delimeters and I don’t completely understand regular expressions (i’ve read a bunch of tutorials but it still doesn’t click)
EDIT:
If regex is the best bet, i just have a hard time understanding how to create an appropriate expression.
I have the following code prepared:
String num = "5+2i";
String[] splitNum = num.split();
And i’m trying to figure out how to write the appropriate regex.
Alternative 1
How about somewhat like this?
If you need to make the sign part of the number, then change the regular expression to
This will make the sign part of the second matching group.
Alternative 2
Alternatively, if you are positively sure that the string is properly formatted and you do not care about the sing of the imaginary part, you could do something like this:
Which is simpler.
Alternative 3
And if you’re not sure of the format of the string, you can still use the regex to validate it:
Alternative 4