2010-08-10 40 views
4

我對編程相當陌生,所以請耐心等待。說我有這樣一個大字符串。按行提取子串

字符串故事= 「這是第一行。\ n」 個
+ 「這是第二行。\ n」 個
+ 「這是第三行\ n」 個
+「這是第四行。\ n「
+」這是第五行「。

我該如何去提取第一行,第四行等?

+2

您應該考慮使用System.getProperty(「line.separator」)作爲換行符,而不是\ n,因爲這將是plattform特有的。 – 2010-08-10 18:24:11

回答

1
String[] lines = story.split('\n'); 

String line_1 = lines[0]; 
String line_4 = lines[3]; 

或類似的規定

5
String[] lines = story.split(System.getProperty("line.separator")); 
String firstLine = lines[0]; 
// and so on 

您可以分割上\n,但這樣你固定* nix系統的行分隔符。如果碰巧你必須在windows上解析,分割\n將不起作用(除非你的字符串是硬編碼的,這會破壞分割的全部目的 - 你知道哪些是預先的行)

+0

+1是第一個提到操作系統依賴的答案。 – 2010-08-10 18:14:48

0

你將字符串分割成一個數組,然後選擇要

String[] arr = story.split("\n") 
arr[0] // first line 
arr[3] // fourth line 
+0

由於不使用\ n – Bozho 2010-08-10 18:01:11

3

您可以將字符串分割成使用split方法,然後索引來得到你想要的線行數組元素:

String story = 
    "This is the first line.\n" + 
    "This is the second line.\n" + 
    "This is the third line\n" + 
    "This is the fourth line.\n" + 
    "This is the fifth line."; 

String[] lines = story.split("\n"); 
String secondLine = lines[1]; 
System.out.println(secondLine); 

結果:

 
This is the second line. 

注:

  • 在Java數組索引從零開始,沒有之一。所以第一行是lines[0]
  • split方法以正則表達式爲參數。
1

如果字符串將是很長的,你可以使用一個BufferedReader和StringReader的組合做一個線在時間:

String story = ...; 
BufferedReader reader = new BufferedReader(new StringReader(story)); 

while ((str = reader.readLine()) != null) { 
    if (str.length() > 0) System.out.println(str); 
} 

否則,分割字符串成數組,如果是使用小足夠Split

String[] lines = story.split("\n"); 
13

如果你想避免創建陣列,可以使用Scanner

Scanner scanner = new Scanner(story); 
while(scanner.hasNextLine()) { 
    System.out.println(scanner.nextLine()); 
} 
+1

+1, – 2010-08-10 18:21:04

+0

+1,它不會返回'ArrayList' – Bozho 2010-08-10 18:26:49