2017-07-26 128 views
0

我想把一個字符串b =「x + yi」分解成兩個整數x和y。Java String使用管道'|'分割多個分隔符

這是我的原始答案。 這裏我去掉末尾的「我」字與子法:

int Integerpart = (int)(new Integer(b.split("\\+")[0])); 
int Imaginary = (int)(new Integer((b.split("\\+")[1]). 
         substring(0, b.split("\\+")[1].length() - 1))); 

但是我發現,剛纔下面的代碼相同的工作:

int x = (int)(new Integer(a.split("\\+|i")[0])); 
int y = (int)(new Integer(a.split("\\+|i")[1])); 

是不是有什麼特別的用「|」?我查了文檔和許多其他問題,但我找不到答案。

+3

在正則表達式中,''''表示_or_ –

+0

如何使用或使用String? Split函數使用參數String,但(「a」|「b」)對我來說看起來不像字符串。 – Sean

+0

split方法將您傳遞給它的字符串解釋爲正則表達式。請參閱[java.lang.String](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-) –

回答

0

您可以使用給定的鏈接瞭解定界符如何工作

How do I use a delimiter in Java Scanner?

另一種替代方式

可以使用useDelimiter(字符串模式)掃描儀類的方法。使用Scanner類的useDelimiter(String pattern)方法。基本上我們使用String分號(;)來標記在Scanner對象的構造函數中聲明的字符串。

字符串「Anne Mills/Female/18」中有三個可能的標記,即姓名,性別和年齡。掃描程序類用於分割字符串並在控制檯中輸出令牌。

import java.util.Scanner; 

/* 
* This is a java example source code that shows how to use useDelimiter(String pattern) 
* method of Scanner class. We use the string ; as delimiter 
* to use in tokenizing a String input declared in Scanner constructor 
*/ 

public class ScannerUseDelimiterDemo { 

    public static void main(String[] args) { 

     // Initialize Scanner object 
     Scanner scan = new Scanner("Anna Mills/Female/18"); 
     // initialize the string delimiter 
     scan.useDelimiter("/"); 
     // Printing the delimiter used 
     System.out.println("The delimiter use is "+scan.delimiter()); 
     // Printing the tokenized Strings 
     while(scan.hasNext()){ 
      System.out.println(scan.next()); 
     } 
     // closing the scanner stream 
     scan.close(); 

    } 
} 
3

split()方法使用控制分割的正則表達式。嘗試 「[+ i]」。大括號標記一組字符,在本例中爲「+」和「i」。

但是,這不會完成你想要做的。你會以「b = x」,「y」,「」結尾。正則表達式還提供搜索和捕獲功能。看看String.matches(String regex)。