如何打印关键字Java后的行范围 让我重新表述我的问题。我正在文件中搜索某个关键字。当我喜欢它时,我需要在这个关键字前面打印一些行,包括它。
我想打印一系列以某个关键字开头的行如何打印关键字Java后的行范围 让我重新表述我的问题。我正在文件中搜索某个关键字。当我喜欢它时,我需要在这个关键字前面打印一些行,包括它。,java,Java,我想打印一系列以某个关键字开头的行 line1 line2 someword line4 line5 找到这个关键字后,我需要打印第1行第2行和这个关键字。 有什么想法吗?我想我理解这个问题。以行分隔输入,逐行搜索关键字。如果找到关键字,则打印前面的n行,后跟关键字 final String input = "line1\nline2\nsomeword\nline4\nline5"; int numberOfLinesToDisplay = 2; String keyword = "som
line1
line2
someword
line4
line5
找到这个关键字后,我需要打印第1行第2行和这个关键字。
有什么想法吗?我想我理解这个问题。以行分隔输入,逐行搜索关键字。如果找到关键字,则打印前面的n行,后跟关键字
final String input = "line1\nline2\nsomeword\nline4\nline5";
int numberOfLinesToDisplay = 2;
String keyword = "someword";
// Split on the newline character
String[] lines = input.split("\n");
// Loop over each line
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
// Checking for the keyword...
if (keyword.equals(line)) {
// Reverse the for loop to print "forwards"
for (int j = numberOfLinesToDisplay; j >= 0; j--) {
// Make sure there is something there
if (i - j >= 0) {
// Simply print it
System.out.println(lines[i - j]);
}
}
}
}
我相信还有更优雅的解决方案,但这适用于所描述的情况
编辑:要从文件中读取,假设性能不是一个紧迫的问题,您可以使用以下内容:未测试
String keyword = "someword";
int numberOfLinesToDisplay = 2;
List<String> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(myFile));
int i = 0;
// Loop over each line
String line;
while ((line = br.readLine()) != null) {
// Add the line to the list
list.add(line);
// Checking for the keyword...
if (keyword.equals(line.trim())) {
// Reverse the for loop to print "forwards"
for (int j = numberOfLinesToDisplay; j >= 0; j--) {
// Make sure there is something there
if (i - j >= 0) {
// Simply print it
System.out.println(list.get(i - j));
}
}
}
i++;
}
Edit2:添加了trim以删除多余的空白。我刚刚更新了@starf创建的上一个示例及其工作。我添加了indexof elemet以查找我的字符串。非常感谢您的帮助
try {
String keyword = "!!!";
int numberOfLinesToDisplay = 8;
ArrayList<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("C:\\some.log"));
int i = 0;
// Loop over each line
String line;
while ((line = br.readLine()) != null) {
// Add the line to the list
list.add(line);
// Checking for the keyword...
int indexfound = line.indexOf(keyword);
// If greater than -1, means we found the word
if (indexfound > -1) {
// Reverse the for loop to print "forwards"
for (int j = numberOfLinesToDisplay; j >= 0; j--) {
// Make sure there is something there
if (i - j >= 0) {
// Simply print it
System.out.println(list.get(i - j));
}
}
}
i++;
}
}catch (IOException ie){
System.out.println("File not found");
}
你能举一个具体的例子说明你的输入和输出吗?到目前为止你做了哪些尝试?向我们展示一些代码,我们可以从那里为您提供指导。你可能还想重新表述你的问题。您说您想打印一些以关键字开头的行,但您的示例说明您想打印包含关键字的行。是哪一行?要打印位于关键字之前还是之后的行?你想在行前还是行后打印关键字?对不起,更新了我的问题我不明白。你到底在问什么?你的解决方案有效现在我需要把它包含在我的代码中需要处理你的第二个示例…无法从中得到结果…@starf indexOf方法检查行中是否包含关键字,而不是它们是否相同。在你的情况下,我的关键字!!!会匹配的!!!。这可能是因为您在读取文件后有额外的空格。它的输出来自某个服务器,这表明在加载数据时出现了一些问题。它始终包含!!!错误前的符号,这就是我使用indexOf的原因method@starfAha,我明白了。在这种情况下,可以使用.contains。