计算Java String中的行数 [英] Count the number of lines in a Java String

查看:683
本文介绍了计算Java String中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Need some compact code for counting the number of lines in a string in Java. The string is to be separated by \r or \n. Each instance of those newline characters will be considered as a separate line. For example -

"Hello\nWorld\nThis\nIs\t"

应该返回4.原型是

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

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

Can someone provide a compact set of statements? I have a solution at here but it is too long, I think. Thank you.

推荐答案

private static int countLines(String str){
   String[] lines = str.split("\r\n|\r|\n");
   return  lines.length;
}

这篇关于计算Java String中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆