2010-08-10 34 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