计算 Java 字符串中的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2850203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count the number of lines in a Java String
提问by Simon Guo
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 -
需要一些紧凑的代码来计算 Java 字符串中的行数。字符串由\r
或分隔\n
。这些换行符的每个实例都将被视为一个单独的行。例如 -
"Hello\nWorld\nThis\nIs\t"
should return 4. The prototype is
应该返回 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.
有人可以提供一组紧凑的语句吗?我在这里有一个解决方案,但我认为它太长了。谢谢你。
采纳答案by Tim Schmelter
private static int countLines(String str){
String[] lines = str.split("\r\n|\r|\n");
return lines.length;
}
回答by aioobe
"Hello\nWorld\nthis\nIs\t".split("[\n\r]").length
You could also do
你也可以这样做
"Hello\nWorld\nthis\nis".split(System.getProperty("line.separator")).length
to use the systems default line separator character(s).
使用系统默认的行分隔符。
回答by vodkhang
I suggest you look for something like this
我建议你寻找这样的东西
String s;
s.split("\n\r");
Look for the instructions here for Java's String Split method
在此处查找有关Java 的 String Split 方法的说明
If you have any problem, post your code
如果您有任何问题,请发布您的代码
回答by dcp
If you have the lines from the file already in a string, you could do this:
如果文件中的行已经在字符串中,则可以执行以下操作:
int len = txt.split(System.getProperty("line.separator")).length;
EDIT:
编辑:
Just in case you ever need to read the contents from a file (I know you said you didn't, but this is for future reference), I recommend using Apache Commonsto read the file contents into a string. It's a great library and has many other useful methods. Here's a simple example:
以防万一您需要从文件中读取内容(我知道您说过没有,但这是供将来参考),我建议使用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;
}
回答by Martijn Courteaux
How about this:
这个怎么样:
String yourInput = "...";
Matcher m = Pattern.compile("\r\n|\r|\n").matcher(yourInput);
int lines = 1;
while (m.find())
{
lines ++;
}
This way you don't need to split the String into a lot of new String objects, which will be cleaned up by the garbage collector later. (This happens when using String.split(String);
).
这样你就不需要将 String 拆分成很多新的 String 对象,这些对象稍后会被垃圾收集器清理掉。(使用 时会发生这种情况String.split(String);
)。
回答by KarlP
Well, this is a solution using no "magic" regexes, or other complex sdk features.
嗯,这是一个不使用“神奇”正则表达式或其他复杂 sdk 功能的解决方案。
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...
如果您想将这种情况 \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++;
}
}
回答by volley
new StringTokenizer(str, "\r\n").countTokens();
Note that this will not count empty lines (\n\n).
请注意,这不会计算空行 (\n\n)。
CRLF (\r\n) counts as single line break.
CRLF (\r\n) 算作单换行符。
回答by Saxintosh
This is a quicker version:
这是一个更快的版本:
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;
}
回答by Veger
A very simple solution, which does not create String objects, arrays or other (complex) objects, is to use the following:
一个不创建 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;
}
Note, that if you use other EOL terminators you need to modify this example a little.
请注意,如果您使用其他 EOL 终止符,则需要稍微修改此示例。
回答by dermoritz
I am using:
我在用:
public static int countLines(String input) throws IOException {
LineNumberReader lineNumberReader = new LineNumberReader(new StringReader(input));
lineNumberReader.skip(Long.MAX_VALUE);
return lineNumberReader.getLineNumber();
}
LineNumberReader
is in the java.io
package: https://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html
LineNumberReader
在java.io
包中:https: //docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html