0

我有一个名为:ComplexNumber 的类,我有一个字符串,我需要将其转换为 ComplexNumber(使用 Java)。

如果我有:“5+3i”或“6-2i”,我该如何正确解析这些字符串。我需要把它变成 2 个变量,剩下的我可以做。

String complexNum = "5+3i"; 

我需要将前一个字符串拆分为两个双精度类型变量 double real = 5;
双图像 = 3;

String complexNum = "6-2i";

我需要将前一个字符串拆分为两个双精度类型变量 double real = 6; 双图像 = -2;

任何人都可以提供示例代码来说明他们将如何执行此操作吗?没有任何空格可以用作分隔符,而且我不完全理解正则表达式(我已经阅读了一堆教程,但它仍然没有点击)


编辑:

如果正则表达式是最好的选择,我只是很难理解如何创建一个合适的表达式。

我准备了以下代码:

String num = "5+2i";
String[] splitNum = num.split();

我试图弄清楚如何编写适当的正则表达式。

4

4 回答 4

6

备选方案 1

有点像这样呢?

String complexNum = "5+3i"; 
String regex = "(\\d+)[+-](\\d+)i";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(complexNum);

if(matcher.find()){
   int real = Integer.parseInt(matcher.group(1));
   int imag = Integer.parseInt(matcher.group(2));
}

如果您需要将符号作为数字的一部分,则将正则表达式更改为

String regex = "(\\d+)([+-]\\d+)i"

这将使符号成为第二个匹配组的一部分。

备选方案 2

或者,如果您确定字符串格式正确并且您不关心虚部的唱法,您可以执行以下操作:

Scanner sc = new Scanner(complexNum).useDelimiter("[i+-]");
int real = sc.nextInt();
int imag = sc.nextInt();

哪个更简单。

备选方案 3

如果您不确定字符串的格式,您仍然可以使用正则表达式来验证它:

if(complexNum.matches("(\\d+)[+-](\\d+)i")) {
  //scanner code here
} else {
   //throw exception or handle the case
}

备选方案 4

String[] tokens = complexNum.split("[i+-]");
int real = Integer.parseInt(tokens[0]);
int imag = Integer.parseInt(tokens[1]);
System.out.println(real +  " " + imag);
于 2012-06-12T05:43:45.213 回答
4

解析复数并不容易,因为 real 和 img 部分还可以包含符号和指数。您可以使用apache-commons-math

ComplexFormat cf = new ComplexFormat();
Complex c = cf.parse("1.110 + 2.222i");
于 2012-06-12T05:47:50.453 回答
0

试试这个 :

    String complexNum = "5+3i"; 
    int j = 0 ;
    String real = getNumber();
    j++;
    String imag = getNumber();   

public String getNumber()
{
      String num ;
      char c;
      int temp;
      for( ; j < complexNum.length() ; j++)
       {
           c = complexNum.charAt(j);
           temp = (int) c;
           if(temp > 57 ||temp < 48)
                 break;
           else
                  num += c;
       }
     return num;
}
于 2012-06-12T05:48:59.240 回答
0

您的正则表达式应如下所示:(\\d+)([-+])(\\d+)iwhere\\d+将匹配任意数量的数字,[+-]将匹配 a+或 a -,并且i简单地匹配自身。()用于选择匹配的字符串部分。

改编自此链接的一些代码

    // Compile the patten.
Pattern p = Pattern.compile("(\\d+)([-+])(\\d+)i");

// Match it.
Matcher m = p.matcher(string);

// Get all matches.
while (m.find() == true)
    System.out.println("Real part " + m.group(1) +
                 " sign " m.group(2) +
         " and imagionary part " + m.group(3));

当然,这些仍然是字符串,所以你需要使用类似的东西

int real = Integer.parseInt(m.group(1))

将值转换为整数形式,您可以使用 if 语句来修复虚部上的符号,例如

if(m.group(2).equals("-"))
    imaginary *= -1;
    //if the value is positive, we don't have to multiply it by anything

更新: Edwin Dalorzo 上面的评论简化了这段代码。使用正则表达式"(\\d+)([+-]\\d+)i"来捕获虚部的符号,然后不需要任何if语句。

于 2012-06-12T06:00:32.667 回答