如何计算 java 中字符串 (6678766566) 中重复的精确双六?

How to get a count of exact double six repeated in a string (6678766566) in java?

我无法构建逻辑来计算字符串中出现的双六。 例如 '6678766566' 此字符串中存在三个双六。

   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 方式。请注意,我们没有做任何 Overlaps.

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);

有很多方法可以做到这一点。部分方式如下所示:

  1. 使用 RegEx 模式,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

  1. 使用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);
        }
    }