2012-03-03 162 views
5

任何人都可以提出一個問題,這個問題一直困擾着我?我有一個Java .jar文件返回從由作爲方法的字符串如下:在Java中拆分一個字符串

integer integer integer block_of_text 

即三個整數其可以是正的或負的,每個由單個空格隔開,然後另一個空間中的塊之前可能包含任何字符但不包含回車符的文字。現在我想我可以讀取一個子字符串,直到每個初始整數的空格字符,然後一次只讀剩下的文本。

我應該補充說,不管它包含什麼,文本塊都不會被分解。

但任何人都可以提出一個更好的選擇?

感謝受訪者。這讓我頭疼!

+0

block_of_text是否包含換行符?更具體地說,Linux/OS X上的'\ n'或Windows上的'\ r \ n'。我認爲是因爲你說任何角色都可能存在。 – 2012-03-03 19:46:35

+0

文本塊可能包含空格? – sgowd 2012-03-03 19:47:30

+0

回車和換行 - 沒有。空間 - 是的。 – 2012-03-03 19:47:52

回答

11

您可以使用String#split(regex,limit) which takes a limit形式:

String s = "123 456 789 The rest of the string"; 
String ss[] = s.split(" ", 4); 
// ss = {"123", "456", "789", "The rest of the string"}; 
+0

我不知道如何使用分割。 – 2012-03-03 19:55:43

7

您可以使用String.split與空間作爲分隔符,並設置4個限制:

String[] result = s.split(" ", 4); 

你也可以使用一個Scanner。這不僅會拆分文本,還會將整數解析爲int。根據是否需要三個整數作爲intString,你可能會發現這更方便:

Scanner scanner = new Scanner(s); 
int value1 = scanner.nextInt(); 
int value2 = scanner.nextInt(); 
int value3 = scanner.nextInt(); 
scanner.skip(" "); 
String text = scanner.nextLine(); 

看到它聯機工作:ideone

+0

+1,便於掃描儀使用。 – maerics 2012-03-03 19:57:29

3

一個簡單的方法(因爲你說在block_of_text中不會有換行符)是使用Scanner。它是基於特定分隔符分解輸入的工具,並將適當類型返回給您。例如,您可以使用方法hasNextInt()nextInt()來檢查輸入中的整數,並實際從流中提取整數。

例如:

Scanner scanner = new Scanner(System.in); // Arg could be a String, another InputStream, etc 
int[] values = new int[3]; 
values[0] = scanner.nextInt(); 
values[1] = scanner.nextInt(); 
... 
String description = scanner.nextLine(); 

你可以使用這個,直到你筋疲力盡的輸入流,並開始,因爲你需要使用的值。

下面是關於如何使用Scanner更多細節:If ... is not an int {

0

最簡單的方式來分割字符串是使用split方法。

String gen = "some texts here"; 
String spt[] = gen.split(" "); //This will split the string gen around the spaces and stores them into the given string array 


要根據你的提問刪除整數,開始從3
數組索引我希望這會有所幫助。