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

后端 未结 7 1498
南旧
南旧 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:24

    You can either split the String on the second String and count the length of the resulting array, it will have one more element that that number of occurrences. Or you can use Pattern and Matcher, which is a slightly more proper approach.

    public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        String first = "/Some object that has a loop in it object/";
        String second = "object";
    
        System.out.println(first.split(Pattern.quote(second)).length - 1);
    
        final Pattern pattern = Pattern.compile(Pattern.quote(second));
        final Matcher matcher = pattern.matcher(first);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
    
        System.out.println(count);
    
    }
    

    Don't forget to use Pattern.quote just in case.

提交回复
热议问题