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

后端 未结 7 1502
南旧
南旧 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:31

    The simplest way is to use indexOf in a loop, advancing the starting index each time that you find the word:

    int ind = 0;
    int cnt = 0;
    while (true) {
        int pos = first.indexOf(second, ind);
        if (pos < 0) break;
        cnt++;
        ind = pos + 1; // Advance by second.length() to avoid self repetitions
    }
    System.out.println(cnt);
    

    This will find the word multiple times if a word contains self-repetitions. See the comment above to avoid such "duplicate" finds.

    Demo on ideone.

提交回复
热议问题