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

后端 未结 7 1566
南旧
南旧 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:14

    try like below...

    String str = "/Some object that has a loop in it object/";
    String findStr = "object";
    int lastIndex = 0;
    int count =0;
    
    while(lastIndex != -1){
    
           lastIndex = str.indexOf(findStr,lastIndex);
    
           if( lastIndex != -1){
                 count ++;
                 lastIndex+=findStr.length();
          }
    }
    System.out.println(count);
    

提交回复
热议问题