需要用Java编写一些简洁的代码来计算字符串中行数。该字符串将以\r
或\n
分隔。每个换行符都将被视为单独的一行。例如 -
"Hello\nWorld\nThis\nIs\t"
应该返回4。原型是:
private static int countLines(String str) {...}
有人能提供一个简洁的语句集吗?我这里有一个解决方案,但是太长了。谢谢。
private static int countLines(String str){
String[] lines = str.split("\r\n|\r|\n");
return lines.length;
}
int count = text.split("\r\n|\r|\n").length;
- kiedysktos这个怎么样:
String yourInput = "...";
Matcher m = Pattern.compile("\r\n|\r|\n").matcher(yourInput);
int lines = 1;
while (m.find())
{
lines ++;
}
这样你就不需要将字符串拆分成很多新的字符串对象,后者将稍后由垃圾回收器清理。(这发生在使用 String.split(String);
时。)
使用Java-11及以上版本,您可以使用以下方式使用String.lines()
API完成相同的操作:
String sample = "Hello\nWorld\nThis\nIs\t";
System.out.println(sample.lines().count()); // returns 4
Returns:
the stream of lines extracted from this 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;
}
请注意,如果您使用其他行尾终止符,您需要稍微修改此示例。
我正在使用:
public static int countLines(String input) throws IOException {
LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(input));
lineNumberReader.skip(Long.MAX_VALUE);
return lineNumberReader.getLineNumber();
}
LineNumberReader
位于java.io
包中: https://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
如果你已经将文件中的行保存到一个字符串中,你可以这样做:
int len = txt.split(System.getProperty("line.separator")).length;
编辑:
以防你以后需要从文件中读取内容(我知道你说你不需要,但这是为了以后参考),我建议使用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;
}
如果您使用的是Java 8,则:
long lines = stringWithNewlines.chars().filter(x -> x == '\n').count() + 1;
(+1的作用是计算如果字符串被修剪后最后一行的字数)
一行解决方案
\r
做了什么? - FelixMpublic static int countLines(String str)
{
if (str == null || str.length() == 0)
return 0;
int lines = 1;
int len = str.length();
for( int pos = 0; pos < len; pos++) {
char c = str.charAt(pos);
if( c == '\r' ) {
lines++;
if ( pos+1 < len && str.charAt(pos+1) == '\n' )
pos++;
} else if( c == '\n' ) {
lines++;
}
}
return lines;
}
Try this one:
public int countLineEndings(String str){
str = str.replace("\r\n", "\n"); // convert windows line endings to linux format
str = str.replace("\r", "\n"); // convert (remaining) mac line endings to linux format
return str.length() - str.replace("\n", "").length(); // count total line endings
}
行数 = countLineEndings(str) + 1
你好 :)
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
private static Pattern newlinePattern = Pattern.compile("\r\n|\r|\n");
public static int lineCount(String input) {
Matcher m = newlinePattern.matcher(input);
int count = 0;
int matcherEnd = -1;
while (m.find()) {
matcherEnd = m.end();
count++;
}
if (matcherEnd < input.length()) {
count++;
}
return count;
}
String.lines()
API。 - Naman