简体   繁体   English

如何限制(iterator.hasNext())迭代次数?

[英]How to Limit while (iterator.hasNext()) iterations?

I am working on Java using the Generex library, to print strings against given regular expressions . 我正在使用Generex库在Java上进行工作,以针对给定的正则表达式打印字符串

Some of the R.Es can generate infinite strings , I just want to handle them, but couldn't yet. 一些R.E可以生成无限字符串 ,我只想处理它们,但还不能。 My code looks like; 我的代码看起来像;

Generex generex = new Generex(regex);
Iterator iterator = generex.iterator();
    System.out.println("Possible strings against the given Regular Expression;\n");
    while (iterator.hasNext()) {
        System.out.print(iterator.next() + " ");
    }

If I input (a)* as a regular expression, the output should look like this 如果我输入(a)*作为正则表达式,则输出应如下所示

a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa ...

How do I limit the result of that loop? 如何限制该循环的结果?

Let's say you wish to print the first 8 items, and then add "..." if there are more items to print. 假设您要打印前8个项目,如果还有更多项目要打印,请添加"..." You can do it as follows: 您可以按照以下步骤进行操作:

int limit = 8;
int current = 0;
while (iterator.hasNext()) {
    if (current != 0) {
        System.out.print(" ");
    }
    System.out.print(iterator.next());
    // If we reach the limit on the number of items that we print,
    // break out of the loop:
    if (++current == limit) {
        break;
    }
}
// When we exit the loop on break, iterator has more items to offer.
// In this case we should print an additional "..." at the end
if (iterator.hasNext()) {
    System.out.print(" ...");
}

In your case, I think the length of the string is much more important than the number of elements printed so I would say the following solution is probably better : 在您的情况下,我认为字符串的长度比打印的元素数重要得多,所以我想说以下解决方案可能更好:

Generex generex = new Generex(regex);
Iterator iterator = generex.iterator();
System.out.println("Possible strings against the given Regular Expression;\n");
StringBuilder sb = new StringBuilder();
int limitOfChars = 100; //for example
while (iterator.hasNext()) {
    String next = iterator.next();
    if (sb.length() + next.length() > limitOfChars) break;
    sb.append(next + " ");
}
System.out.println(sb.toString() + " ... ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM