java行数_计算Java字符串中的行数

计算Java字符串中的行数

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

"Hello\nWorld\nThis\nIs\t"

应该返回4。原型是

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

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

Simon Guo asked 2020-06-22T23:49:37Z

15个解决方案

74 votes

private static int countLines(String str){

String[] lines = str.split("\r\n|\r|\n");

return lines.length;

}

Tim Schmelter answered 2020-06-22T23:49:41Z

25 votes

这个怎么样:

String yourInput = "...";

Matcher m = Pattern.compile("\r\n|\r|\n").matcher(yourInput);

int lines = 1;

while (m.find())

{

lines ++;

}

这样,您无需将String拆分为许多新的String对象,这些对象稍后将由垃圾收集器清理。 (使用String.split(String);时会发生这种情况)。

Martijn Courteaux answered 2020-06-22T23:50:05Z

16 votes

一个不创建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;

}

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

Veger answered 2020-06-22T23:50:30Z

10 votes

如果文件中的行已经在字符串中,则可以执行以下操作:

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;

}

dcp answered 2020-06-22T23:50:59Z

7 votes

我在用:

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]

dermoritz answered 2020-06-22T23:51:23Z

4 votes

如果您使用Java 8,则:

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

(如果字符串被修剪,最后+1表示最后一行)

一线解决方案

Gleb S answered 2020-06-22T23:51:52Z

4 votes

对于JDK / 11,您可以使用Returns:

the stream of lines extracted from this string 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

Naman answered 2020-06-22T23:52:20Z

3 votes

这是一个更快的版本:

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;

}

Saxintosh answered 2020-06-22T23:52:40Z

1 votes

试试这个:

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

问候 :)

Zephram answered 2020-06-22T23:53:08Z

1 votes

//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结尾,这将计算最后一行

user939857 answered 2020-06-22T23:53:28Z

0 votes

嗯,这是一个不使用“魔术”正则表达式或其他复杂SDK功能的解决方案。

显然,正则表达式匹配器在现实生活中可能会更好,因为它编写起来更快。 (它也可能没有错误...)

另一方面,您应该能够了解这里发生的事情...

如果要将个案\ r \ n作为单个换行符(msdos-convention)处理,则必须添加自己的代码。 提示,您需要另一个变量来跟踪先前匹配的字符...

int lines= 1;

for( int pos = 0; pos < yourInput.length(); pos++){

char c = yourInput.charAt(pos);

if( c == "\r" || c== "\n" ) {

lines++;

}

}

KarlP answered 2020-06-22T23:54:02Z

0 votes

new StringTokenizer(str, "\r\n").countTokens();

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

CRLF(\ r \ n)计为单个换行符。

volley answered 2020-06-22T23:54:26Z

0 votes

"Hello\nWorld\nthis\nIs\t".split("[\n\r]").length

你也可以

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

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

aioobe answered 2020-06-22T23:54:50Z

0 votes

此方法将分配一个char数组,而不是在string.length()上进行迭代,而应使用它,因为length()使用Unicode字符数而不是char。

int countChars(String str, char chr) {

char[] charArray = str.toCharArray();

int count = 0;

for(char cur : charArray)

if(cur==chr) count++;

return count;

}

Ghandhikus answered 2020-06-22T23:55:10Z

-2 votes

我建议你寻找这样的东西

String s;

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

在此处查找有关Java的String Split方法的说明

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

vodkhang answered 2020-06-22T23:55:39Z

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值