Java 逐行提取子串
我对编程相当陌生,所以请容忍我。假设我有一根像这样的大绳子 String story=“这是第一行。\n”Java 逐行提取子串,java,Java,我对编程相当陌生,所以请容忍我。假设我有一根像这样的大绳子 String story=“这是第一行。\n” +“这是第二行。\n” +“这是第三行\n” +“这是第四行。\n” +“这是第五行。” 我将如何提取第一行、第四行等等 String[] lines = story.split('\n'); String line_1 = lines[0]; String line_4 = lines[3]; 或者类似的东西 String[] lines = story.split(System.g
+“这是第二行。\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
上拆分将不起作用(当然,除非您的字符串是硬编码的,这破坏了拆分的全部目的-您事先知道哪些是行)您可以将字符串拆分为一个数组,然后选择所需的数组元素
String[] arr = story.split("\n")
arr[0] // first line
arr[3] // fourth line
您可以使用方法将字符串拆分为行,然后索引以获得所需的行:
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中,索引数组从零开始,而不是从一开始。所以第一行是
行[0]
- split方法将正则表达式作为其参数
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");
如果要避免创建数组,可以使用
它不返回一个<代码> ARAYLISTAB/CODE >。您应该考虑使用Stask.GETFACTS(“Leal.S隔除器”)作为断线,而不是\n,因为这将是PrtSt窗形体特定的。
Scanner scanner = new Scanner(story);
while(scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}