2014-11-03 54 views
0

簡而言之,我目前正在使用的程序要求我分割我的掃描儀輸入(例如:2 Ham和Cheese 5.5)。它應該按照雜貨店訂單來閱讀,並將其分成三個數組。我應該使用string.split,並且能夠將此輸入分成三部分,而不管中間字符串中的空格。如何將掃描儀輸入分割爲(數字)(字符串與空格)(數字)

實施例輸入#1:2蘋果0.9

實施例輸出#1

蘋果

0.9

示例輸入#2 :2個月再蘋果0.9

示例輸出#2

更多蘋果

0.9

如何做到這一點?無論何時我使用string.split來分割有空間的地方,當我只需要在數字和字符串之間進行拆分時,它就會拆分「more」和「apples」。

謝謝。

回答

1

您可以嘗試.split("[^0-9]+"),但這會丟棄數字之間的信息。

我想你應該切換到使用Matcher,從Pattern得到的是這樣的:

Pattern p = Pattern.compile("([0-9.]+)([^0-9]+)([0-9.]+)"); 
Matcher m = p.matcher("30 apples and pears 0.29"); 
if (m.matches()) { 
    String number = m.group(1); 
    String product = m.group(2); 
    String price = m.group(3); 
    // Continue parsing numbers ... 
} 
3

試試這個(言自明):

String str = "2 More Apples 0.9"; 
int fistSpaceIndex = str.indexOf(" "); 
int lastSpaceIndex = str.lastIndexOf(" "); 
int quantity = Integer.parseInt(str.substring(0, fistSpaceIndex)); 
String name = str.substring(fistSpaceIndex, lastSpaceIndex); 
Double cost = Double.parseDouble(str.substring(lastSpaceIndex)); 
System.out.println(quantity + " " + name + " " + cost); 

分割字符串的空間,那麼之前的一切第一個空間是數量,在最後一個空間之後的所有東西都是成本,而改變之間的任何東西都是名稱。

0

它在你的例子不是明擺着的投入將永遠是這樣的: 控管數量名稱價格 這樣你就可以使用string.split,獲得第一個和最後一個號碼,concatinate其他絃樂與空間T [ 2] -t [n-1]