一种方法是从字符串创建StringReader
,将其包装在BufferedReader
中,并使用它读取行。或者,你可以只劈在\n
得到线,当然...
String[] allLines = text.split("\n");
List<String> selectedLines = new ArrayList<String>();
for (int i = 0; i < allLines.length; i += 100)
{
selectedLines.add(allLines[i]);
}
这比使用BufferedReader
简单的代码,但它确实意味着其在内存中完成分割字符串(还有原创,当然至少暂时)。在适应从其他来源(例如文件)读取行的方面,它也不太灵活。但如果这是你需要的,这是非常简单的:)
编辑:如果启动索引也需要,它变得略微更复杂...但不是太糟糕。你可能想在一个类来封装“开头和行”,但为了简便起见:
String[] allLines = text.split("\n");
List<String> selectedLines = new ArrayList<String>();
List<Integer> selectedIndexes = new ArrayList<Integer>();
int index = 0;
for (int i = 0; i < allLines.length; i++)
{
if (i % 100 == 0)
{
selectedLines.add(allLines[i]);
selectedIndexes.add(index);
}
index += allLines[i].length + 1; // Add 1 for the trailing "\n"
}
给出的开始索引和行。当然,你可以通过添加得到的结束索引线路长度:)
对不起,我没有把这个问题,但它有可能获得每100行的开始索引和结束索引? – AlexPriceAP
@AlexPriceAp:当然 - 但你想要他们在哪里?目前将它们放入单独的ArrayList中... –
单独的ArrayList很好。我想要开始和结束的原因是我可以将它们用作我正在开发的SyntaxHighlighter的边界,所以我可以突出显示每100(当前)行,因为我正在为移动设备开发,并且它可能会很慢与大文件! – AlexPriceAP