Sim*_*Guo 47 java string lines
需要一些紧凑的代码来计算Java中字符串中的行数.该字符串将由\r或分隔\n.这些换行符的每个实例都将被视为一个单独的行.例如 -
"Hello\nWorld\nThis\nIs\t"
Run Code Online (Sandbox Code Playgroud)
应该返回4.原型是
private static int countLines(String str) {...}
Run Code Online (Sandbox Code Playgroud)
有人能提供一套紧凑的陈述吗?我在这里有一个解决方案,但是我觉得它太长了.谢谢.
Tim*_*ter 75
private static int countLines(String str){
String[] lines = str.split("\r\n|\r|\n");
return lines.length;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*aux 25
这个怎么样:
String yourInput = "...";
Matcher m = Pattern.compile("\r\n|\r|\n").matcher(yourInput);
int lines = 1;
while (m.find())
{
lines ++;
}
Run Code Online (Sandbox Code Playgroud)
这样您就不需要将String拆分为许多新的String对象,稍后将由垃圾收集器对其进行清理.(使用时会发生这种情况String.split(String);).
Veg*_*ger 16
一个非常简单的解决方案,它不会创建String对象,数组或其他(复杂)对象,而是使用以下方法:
public static int countLines(String str) {
if(str == null || str.isEmpty())
{
return 0;
}
int lines = 1;
int pos = 0;
while ((pos = str.indexOf("\n", pos) + 1) != 0) {
lines++;
}
return lines;
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您使用其他EOL终结器,则需要稍微修改此示例.
Nam*_*man 16
使用 Java-11 及更高版本,您可以使用String.lines()API执行相同操作,如下所示:
String sample = "Hello\nWorld\nThis\nIs\t";
System.out.println(sample.lines().count()); // returns 4
Run Code Online (Sandbox Code Playgroud)
API 文档将以下内容作为描述的一部分:-
Run Code Online (Sandbox Code Playgroud)Returns: the stream of lines extracted from this string
dcp*_*dcp 10
如果文件中的行已经存在于字符串中,则可以执行以下操作:
int len = txt.split(System.getProperty("line.separator")).length;
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您需要从文件中读取内容(我知道您说没有,但这是为了将来参考),我建议使用Apache Commons将文件内容读入字符串.这是一个很棒的图书馆,还有许多其他有用的方法.这是一个简单的例子:
import org.apache.commons.io.FileUtils;
int getNumLinesInFile(File file) {
String content = FileUtils.readFileToString(file);
return content.split(System.getProperty("line.separator")).length;
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 Java 8,则:
long lines = stringWithNewlines.chars().filter(x -> x == '\n').count() + 1;
Run Code Online (Sandbox Code Playgroud)
(如果字符串被修剪,最后+1是计算最后一行)
一条线解决方案
我在用:
public static int countLines(String input) throws IOException {
LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(input));
lineNumberReader.skip(Long.MAX_VALUE);
return lineNumberReader.getLineNumber();
}
Run Code Online (Sandbox Code Playgroud)
LineNumberReader是在java.io包:https://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html