shell
shell

Reputation: 401

Java How to get start and end of an element in an ArrayList

I have some dynamic values in an ArrayList

ClassnameOne <!----Begin---->
Classnametwo <!----Begin---->
Classnamethree <!----Begin---->
Classnamethree <!----End---->
Classnametwo <!----End--->
ClassnameOne <!----End---->

What I want to do is to get the beginning occurrence of an element and when it ends. So for example ClassnameOne would be 5, Classnametwo would be 3. This is what I have done so far:

ArrayList<String> one = new ArrayList<String>();
for (int i = 0; i < one.size(); i++) {
    if(one.get(i).contains("<!----End---->") && one.get(i).equals(one.get(i+1))) {
        break;
    } else {
        count++;
        System.out.println(one.get(i));
    }
    System.out.println(count);
}

This doesn't give the right answer. Can you please help?

Upvotes: 0

Views: 920

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

ArrayList<String> one = new ArrayList<String>();
for (int starti = 0; starti < one.size(); ++starti) {
    String[] words = one.get(starti).split(" ", 2);
    if (words[1].equals("<!----Begin---->")) {
        int n = 0;
        String sought = words[0] + " " + "<!----End---->";
        for (int endi = starti + 1; endi < one.size(); ++endi) {
            if (one.get(endi).equals(sought) {
                n = endi - starti;
                break;
            }
        }
        System.out.printf("%s at %d covers %d lines.%n", words[0], starti, n);
    }
}

Assuming that the names do not repeat, otherwise a stack (or such) would to be needed.

Upvotes: 1

Related Questions