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

后端 未结 7 1501
南旧
南旧 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

提交回复
热议问题