在 Java 中,给定一个多行字符串和该字符串中的字符索引(例如 matcher.start() 调用的结果),在字符串中查找该字符索引的行号和列号的最有效方法是什么?
例如
String s = "abc\ndef\nghi\n";
int i = 5; // i.e. the e character (since we start at 0 and count newlines)
// Do something
System.out.println("Line: " + line + " Column: " + column);
应该产生
Line: 2 Column 2
我为此继承的代码使用 s.substring(p)
获取字符串的前缀直到字符索引,在换行符上拆分它,然后计算拆分返回的行数,以及 split 返回的最终数组元素中的字符数。这工作正常,但随着前缀变长而变慢(我想在一个紧密的循环中使用它)。
最佳答案
当您可以迭代原始字符串并避免任何对象分配时,为什么需要使用子字符串并生成新字符串并对片段进行标记?
int c = 1;
int line = 1, col = 1;
while (c <= i)
{
if (string.charAt(c) == '\n')
{
++line;
col = 1;
} else {
++col;
}
}
关于java - 在长 java 字符串中查找行号和列号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24731649/