gpt4 book ai didi

java - 从字符串中读取第 n 行

转载 作者:行者123 更新时间:2023-12-02 08:51:30 27 4
gpt4 key购买 nike

我正在尝试读取字符串的第 7 行,以便我可以过滤所需的文本,但不能获取更多文本。(假设我有 n 行)。

class Lastnthchar {

public static void main(String[] args) {
// TODO Auto-generated method stub


String alldata =" FORM"+"\n"+
" to get all data"+"\n"+
" PART A is mandatory"+"\n"+
" enclose all Certificate"+"\n"+
" Certificate No. SFDSFDFS Last updated on 12-Jun-2009"+"\n"+
" Name and address"+"\n"+
" Lisa Lawerence"+"\n"+
" 10/3 TOP FLOOR, Street no 22 ,NewYork"+"\n"+
" residence"+"\n"+
" zip-21232"+"\n"+
" C 78,New York"+"\n"+
" US"+"\n"+
" US"+"\n"+
" "+"\n"+
" worldwide";

String namerequired = new String ();

//BufferedReader br = new BufferedReader(alldata);
int lineno = 0;
for(lineno = 0; lineno <alldata.length(); lineno ++)
{
//what should i do?
}
}

}

所以如果有任何解决方案请帮忙。

最佳答案

alldata.length() 将返回字符串的长度(即字符数),而不是行数。

要获取第 n 行,您需要在换行符处拆分字符串,例如alldata.split("\n")[6] 获取第 7th 行(前提是至少有 7 行)。这还假设您的字符串中有换行符 (\n),而不仅仅是回车符 (\r)。如果您想单独或组合拆分,可以将split()的参数更改为“\r\n|\n|\r”。如果要跳过空行,可以按至少一个换行符或回车符的任意顺序进行拆分,例如“[\r\n]+”

示例:

System.out.println("--- Input:");
String input = "A\nB\rC\n\nD\r\nE";
System.out.println(input);

System.out.println("--- 4th element, split by \\n:");
System.out.println(input.split("\n")[3]); //3rd element will be "D\r"
System.out.println("--- 4th element, split by \\r\\n|\\n|\\r:");
System.out.println(input.split("\r\n|\n|\r")[3]); //3rd element will be an empty string
System.out.println("--- 4th element, split by [\\r\\n]+:");
System.out.println(input.split("[\r\n]+")[3]); //3rd element will be "D"
System.out.println("--- END");

输出:

--- Input:
A
B
C

D
E
--- 4th element, split by \n:
D

--- 4th element, split by \r\n|\n|\r:

--- 4th element, split by [\r\n]+:
D
--- END

或者,如果您正在从某个流(例如从文件)读取文本,您可以使用 BufferedReader#readLine() 并计算行数。此外,您可以使用 FileReaderStringReader 等初始化 BufferedReader,具体取决于您从何处读取输入。

如果您从控制台读取,则 Console 类还有一个 readLine() 方法。

关于java - 从字符串中读取第 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26357469/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com