如何限制 while (iterator.hasNext()) 迭代?
How to Limit while (iterator.hasNext()) iterations?
我正在 Java 使用 Generex 库,根据给定的正则表达式打印字符串。
有些R.Es可以生成无限字符串,我只想处理它们,但还不能。
我的代码看起来像;
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() + " ");
}
如果我输入 (a)* 作为正则表达式,输出应该如下所示
a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa ...
如何限制该循环的结果?
假设您希望打印前 8 项,然后如果要打印更多项则添加 "..."
。您可以按如下方式进行:
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(" ...");
}
在你的情况下,我认为字符串的长度比打印的元素数量重要得多,所以我认为以下解决方案可能更好:
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() + " ... ");
我正在 Java 使用 Generex 库,根据给定的正则表达式打印字符串。
有些R.Es可以生成无限字符串,我只想处理它们,但还不能。 我的代码看起来像;
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() + " ");
}
如果我输入 (a)* 作为正则表达式,输出应该如下所示
a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa ...
如何限制该循环的结果?
假设您希望打印前 8 项,然后如果要打印更多项则添加 "..."
。您可以按如下方式进行:
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(" ...");
}
在你的情况下,我认为字符串的长度比打印的元素数量重要得多,所以我认为以下解决方案可能更好:
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() + " ... ");