计算字符串x的实例,直到找到字符串y

时间:2015-07-01 22:59:19

标签: java eclipse windows

我一直试图这样做大约一个小时左右,但只设法编写了一些只能算数或只能搜索的东西。我的目标是组合一些不仅会查找特定字符串(让我们称之为“STRINGTOFIND”)的东西,还要计算另一个特定的实例(让我们称之为“STRINGTOCOUNT”)字符串,直到找到“STRINGTOFIND”。

以下是我的计算方法:

int count = 0;
Scanner scanner = new Scanner("example.xml");
while (scanner.hasNextLine()) {
   String nextToken = scanner.next();
   if (nextToken.equalsIgnoreCase("STRINGTOCOUNT"))
   count++;
}

这就是我找到的方式(我想找到它的线条):

int lineN = 1; //set to 1 for the loop to return correct line number
Scanner scanner = new Scanner("example.xml");
while (scanner.hasNextLine()) {
    lineNum++;
    if("STRINGTOFIND".equals(scanner.nextLine().trim())) { 
        System.out.println("found on line: "+lineNum);
    }
}

我考虑过寻找STRINGTOFIND,获取它的行号并让第一个扫描仪只计算STRINGTOCOUNT直到该行,但我的编程技巧不足以令人遗憾。所以我的问题是,因为我已经有了代码来执行我想要做的事情只有一个,我该如何组合这些?

1 个答案:

答案 0 :(得分:1)

你只需在循环中使用两个if语句。

boolean foundString = false;
int count = 0, lineNum = 1;
while(scanner.hasNextLine()){
    String line = scanner.nextLine();
    if(line.equals("STRINGTOFIND")){
        foundString = true;
        break; // Break out of the loop
    }
    else if(line.equals("STRINGTOCOUNT")) count++;
    lineNum++;
}
// Code that uses "foundString" and/or "lineNum"

此代码将计算与“STRINGTOCOUNT”匹配的行数,直到找到与“STRINGTOFIND”匹配的行或文件没有更多未读取的行(lineNum将包含发生此行的行号)。 / p>