59

需要一些紧凑的代码来计算 Java 中字符串的行数。字符串用\ror分隔\n。这些换行符的每个实例都将被视为单独的行。例如 -

"Hello\nWorld\nThis\nIs\t"

应该返回 4。原型是

private static int countLines(String str) {...}

有人可以提供一组紧凑的陈述吗?我在这里有一个解决方案,但我认为它太长了。谢谢你。

4

16 回答 16

86
private static int countLines(String str){
   String[] lines = str.split("\r\n|\r|\n");
   return  lines.length;
}
于 2010-05-17T15:14:38.700 回答
28

这个怎么样:

String yourInput = "...";
Matcher m = Pattern.compile("\r\n|\r|\n").matcher(yourInput);
int lines = 1;
while (m.find())
{
    lines ++;
}

这样就不需要把String拆分成很多新的String对象,后面会被垃圾回收器清理掉。(使用 时会发生这种情况String.split(String);)。

于 2010-05-17T15:42:24.797 回答
19

一个不创建字符串对象、数组或其他(复杂)对象的非常简单的解决方案是使用以下内容:

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;
}

请注意,如果您使用其他 EOL 终结器,则需要稍微修改此示例。

于 2013-09-15T19:07:10.273 回答
18

使用 Java-11 及更高版本,您可以使用String.lines()API 执行相同操作,如下所示:

String sample = "Hello\nWorld\nThis\nIs\t";
System.out.println(sample.lines().count()); // returns 4

API 文档将以下内容作为描述的一部分:-

Returns:
the stream of lines extracted from this string
于 2018-05-31T19:23:04.210 回答
12

我在用:

public static int countLines(String input) throws IOException {
    LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(input));
    lineNumberReader.skip(Long.MAX_VALUE);
    return lineNumberReader.getLineNumber();
}

LineNumberReaderjava.io包中:https ://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html

于 2014-11-06T12:19:54.590 回答
11

如果文件中的行已经在字符串中,则可以这样做:

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;
}
于 2010-05-17T15:15:29.370 回答
8

如果您使用 Java 8,那么:

long lines = stringWithNewlines.chars().filter(x -> x == '\n').count() + 1;

(如果字符串被修剪,最后+1是计算最后一行)

一条线解决方案

于 2018-01-12T09:44:02.837 回答
3

这是一个更快的版本:

public 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;
}
于 2012-02-06T13:46:53.047 回答
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;
}

如果它不以 cr/lf cr lf 结尾,这将计算最后一行

于 2018-08-05T14:27:41.850 回答
1

试试这个:

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

问候 :)

于 2017-06-02T16:07:30.160 回答
0

Well, this is a solution using no "magic" regexes, or other complex sdk features.

Obviously, the regex matcher is probably better to use in real life, as its quicker to write. (And it is probably bug free too...)

On the other hand, You should be able to understand whats going on here...

If you want to handle the case \r\n as a single new-line (msdos-convention) you have to add your own code. Hint, you need another variable that keeps track of the previous character matched...

int lines= 1;

for( int pos = 0; pos < yourInput.length(); pos++){
    char c = yourInput.charAt(pos);
    if( c == "\r" || c== "\n" ) {
        lines++;
    }
}
于 2010-05-17T16:00:09.640 回答
0
"Hello\nWorld\nthis\nIs\t".split("[\n\r]").length

你也可以做

"Hello\nWorld\nthis\nis".split(System.getProperty("line.separator")).length

使用系统默认的行分隔符。

于 2010-05-17T15:12:34.903 回答
0
new StringTokenizer(str, "\r\n").countTokens();

请注意,这不会计算空行 (\n\n)。

CRLF (\r\n) 算作单行换行符。

于 2010-05-17T18:49:44.307 回答
0

怎么样StringUtils.countMatches()

在你的情况下

StringUtils.countMatches("Hello\nWorld\nThis\nIs\t", "\n") + StringUtils.countMatches("Hello\nWorld\nThis\nIs\t", "\r") + 1

应该可以正常工作。

于 2022-01-04T08:08:44.810 回答
0

此方法将分配一个字符数组,应该使用它而不是遍历 string.length() 因为 length() 使用 Unicode 字符数而不是字符数。

int countChars(String str, char chr) {
    char[] charArray = str.toCharArray();
    int count = 0;
    for(char cur : charArray)
        if(cur==chr) count++;
    return count;
}
于 2016-12-17T21:19:50.030 回答
-2

我建议你找这样的东西

String s; 
s.split("\n\r");

在此处查找Java 的字符串拆分方法的说明

如果您有任何问题,请发布您的代码

于 2010-05-17T15:12:38.930 回答