需要一些紧凑的代码来计算 Java 中字符串的行数。字符串用\r
or分隔\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;
}
这个怎么样:
String yourInput = "...";
Matcher m = Pattern.compile("\r\n|\r|\n").matcher(yourInput);
int lines = 1;
while (m.find())
{
lines ++;
}
这样就不需要把String拆分成很多新的String对象,后面会被垃圾回收器清理掉。(使用 时会发生这种情况String.split(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 终结器,则需要稍微修改此示例。
使用 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
我在用:
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是计算最后一行)
一条线解决方案
这是一个更快的版本:
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;
}
//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 结尾,这将计算最后一行
试试这个:
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
问候 :)
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++;
}
}
"Hello\nWorld\nthis\nIs\t".split("[\n\r]").length
你也可以做
"Hello\nWorld\nthis\nis".split(System.getProperty("line.separator")).length
使用系统默认的行分隔符。
new StringTokenizer(str, "\r\n").countTokens();
请注意,这不会计算空行 (\n\n)。
CRLF (\r\n) 算作单行换行符。
怎么样StringUtils.countMatches()
。
在你的情况下
StringUtils.countMatches("Hello\nWorld\nThis\nIs\t", "\n") + StringUtils.countMatches("Hello\nWorld\nThis\nIs\t", "\r") + 1
应该可以正常工作。
此方法将分配一个字符数组,应该使用它而不是遍历 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;
}