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

后端 未结 7 1505
南旧
南旧 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:18

    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.

提交回复
热议问题