我對編程相當陌生,所以請耐心等待。說我有這樣一個大字符串。按行提取子串
字符串故事= 「這是第一行。\ n」 個
+ 「這是第二行。\ n」 個
+ 「這是第三行\ n」 個
+「這是第四行。\ n「
+」這是第五行「。
我該如何去提取第一行,第四行等?
我對編程相當陌生,所以請耐心等待。說我有這樣一個大字符串。按行提取子串
字符串故事= 「這是第一行。\ n」 個
+ 「這是第二行。\ n」 個
+ 「這是第三行\ n」 個
+「這是第四行。\ n「
+」這是第五行「。
我該如何去提取第一行,第四行等?
String[] lines = story.split('\n');
String line_1 = lines[0];
String line_4 = lines[3];
或類似的規定
String[] lines = story.split(System.getProperty("line.separator"));
String firstLine = lines[0];
// and so on
您可以分割上\n
,但這樣你固定* nix系統的行分隔符。如果碰巧你必須在windows上解析,分割\n
將不起作用(除非你的字符串是硬編碼的,這會破壞分割的全部目的 - 你知道哪些是預先的行)
+1是第一個提到操作系統依賴的答案。 – 2010-08-10 18:14:48
你將字符串分割成一個數組,然後選擇要
String[] arr = story.split("\n")
arr[0] // first line
arr[3] // fourth line
由於不使用\ n – Bozho 2010-08-10 18:01:11
您可以將字符串分割成使用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.
注:
lines[0]
。如果字符串將是很長的,你可以使用一個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");
您應該考慮使用System.getProperty(「line.separator」)作爲換行符,而不是\ n,因爲這將是plattform特有的。 – 2010-08-10 18:24:11