How to find how many times does a string object repeat in java?

后端 未结 7 1500
南旧
南旧 2021-01-21 18:45

I have to String objects:

String first = \"/Some object that has a loop in it object/\";
String second = \"object\";

What I need to do is find

相关标签:
7条回答
  • 2021-01-21 19:33

    Use regex, example:

    import java.util.regex.*;
    
    class Test {
        public static void main(String[] args) {
            String hello = "HelloxxxHelloxxxHello"; //String you want to 'examine'
            Pattern pattern = Pattern.compile("Hello"); //Pattern string you want to be matched
            Matcher  matcher = pattern.matcher(hello); 
    
            int count = 0;
            while (matcher.find())
                count++; //count any matched pattern
    
            System.out.println(count);    // prints how many pattern matched
        }
    }
    

    source: java regex match count

    0 讨论(0)
提交回复
热议问题