如何解决java - 如何在java中的字符串6678766566中重复精确的双六计数?
我无法构建一个逻辑来获取字符串中出现的双六的计数。 例如 '6678766566' 在这个字符串中有三个双六。
解决方法
有很多方法可以做到这一点。部分方式如下所示:
-
使用正则表达式模式,
6(?=6)
和 Java Regex API:-
Stream
版本:
import java.util.regex.Pattern; public class Main { public static void main(String[] args) { long count66 = Pattern.compile("6(?=6)") .matcher("6678766566") .results() .count(); System.out.println(count66); } }
-
非
Stream
版本:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { int count66 = 0; Matcher matcher = Pattern.compile("6(?=6)").matcher("6678766566"); while (matcher.find()) { count66++; } System.out.println(count66); } }
-
请注意,(?=(regex))
用于 Positive Lookahead。
-
使用
String#indexOf
:public class Main { public static void main(String[] args) { int count66 = 0; String str = "6678766566"; for (int i = 0; i < str.length(); i++) { int index = str.indexOf("66",0); if (index != -1) { count66++; str = str.substring(index + 1); } } System.out.println(count66); } }
String str = "6678766566";
int count = 0;
for(int i=0; i<str.length()-1; i++){
if(str.charAt(i)=='6' && str.charAt(i+1)=='6'){
count++;
i++;
}
}
System.out.println(count);
,
您可以使用 Pattern api:
String s = "6678766766";
Pattern p = Pattern.compile("66");
Matcher m = p.matcher(s);
int count = 0;
while(m.find()) {
count++;
}
System.out.println(count);
注意:要包含重叠,请使用模式 (6)(?=(6))
。这将为 666
提供计数 2。
为了让它更有趣,您可以使用 RegEx 方式。请注意,我们不会进行任何重叠。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Match {
public static void main(String[] args) {
final String regex = "(66)";
final String string = "667876656666";
final Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
//prints 4
System.out.println("Number of matches: " + matcher.results().count());
}
}
也包括重叠:
final String string = "667876656666767666";
int i = 0;
int count = 0;
while (i < string.length() -1) {
if (string.charAt(i) == '6' && string.charAt(i+1) == '6') {
count++;
}
i++;
}
// prints 7
System.out.println("Number of matches including overlaps: " + count);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。