简体   繁体   中英

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

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 how many times does the second object repeat in the first object, can you please show me how to do that?

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.

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 .

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

Use this :

 String first = "/Some object that has a loop in it object/";
     String second = "object";
     Pattern pattern = Pattern.compile(second);
     Matcher matcher = pattern.matcher(first) ;
     long count = 0;
     while(matcher.find()) {
         count ++;

     }
     System.out.println(count);

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);

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.

I know this is an older topic, but off the top of my head, you could use recursion:

// Recursive routine to find the xth repeat of a string
public int atIndex(String searchin, String searchfor, int whichone, int pos) {
    return atIndex(searchin, searchfor, whichone, pos, 0);
}

public int atIndex(String searchin, String searchfor, int whichone, int pos, int recursed) {
    return (whichone>0?atIndex(searchin, searchfor, --whichone, searchin.indexOf(searchfor,pos)+1,++recursed):(recursed==0?-1:pos-1));
}

I'm new at Java, so there may be a speed or resources issue that I'm not aware of, but a little bit of testing should suss out any problems.

To call it, you might use:

    String HL7Test="MSH|^~\\&|EPIC|EPICADT|SMS|SMSADT|199912271408|CHARRIS|ADT^A04|1817457" ;
    System.out.println(atIndex(HL7Test, "|", 4, 0));

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM