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

后端 未结 7 1580
南旧
南旧 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:06

    Use this single line which utilizes regular expressions in the background:

    String[] parts = first.split(second);
    

    String second occurs (parts.length - 1) times in String first. That's all.

    EDIT:

    To prevent unwanted results that could occur in the case of String second might contain regex-specific characters, you can use Pattern.quote(second) when passing it to split() method, as one of the commentators suggested.

提交回复
热议问题