[英]Make a method to divide a string in java
我有一個名為:ComplexNumber的類,並且有一個需要轉換為ComplexNumber(使用Java)的字符串。
如果我有:“ 5 + 3i”或“ 6-2i”,我該如何適當地解析這些字符串。 我需要將其設置為2個變量,其余的我都可以做。
String complexNum = "5+3i";
我需要將前面的字符串分成兩個double類型變量double real = 5;
雙倍成像= 3;
String complexNum = "6-2i";
我需要將前面的字符串分成兩個double類型的變量double real = 6; 雙倍成像= -2;
誰能提供示例代碼說明他們將如何執行此操作? 沒有任何空格可以用作分隔符,我也不完全了解正則表達式(我讀過很多教程,但仍然沒有點擊)
編輯:
如果正則表達式是最好的選擇,我只是很難理解如何創建適當的表達式。
我准備了以下代碼:
String num = "5+2i";
String[] splitNum = num.split();
我正在嘗試弄清楚如何編寫適當的正則表達式。
這樣子怎么樣?
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"
這將使符號成為第二個匹配組的一部分。
或者,如果您確定該字符串格式正確,並且您不關心虛部的唱歌,則可以執行以下操作:
Scanner sc = new Scanner(complexNum).useDelimiter("[i+-]");
int real = sc.nextInt();
int imag = sc.nextInt();
哪個更簡單。
而且,如果不確定字符串的格式,仍然可以使用正則表達式對其進行驗證:
if(complexNum.matches("(\\d+)[+-](\\d+)i")) {
//scanner code here
} else {
//throw exception or handle the case
}
String[] tokens = complexNum.split("[i+-]");
int real = Integer.parseInt(tokens[0]);
int imag = Integer.parseInt(tokens[1]);
System.out.println(real + " " + imag);
解析復數並不是那么容易,因為實數和img部分還可以包含一個符號和一個指數。 您可以使用apache-commons-math 。
ComplexFormat cf = new ComplexFormat();
Complex c = cf.parse("1.110 + 2.222i");
嘗試這個 :
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;
}
您的正則表達式應如下所示: (\\\\d+)([-+])(\\\\d+)i
其中\\\\d+
將匹配任意數量的數字, [+-]
將匹配+
或-
和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
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.