java - Count instances of string x until string y is found -


i've been trying hour or managed code can count or can search. goal put not specific string(let's call "stringtofind") count instances of specific(let's call "stringtocount") string until finds "stringtofind".

here's how count:

int count = 0; scanner scanner = new scanner("example.xml"); while (scanner.hasnextline()) {    string nexttoken = scanner.next();    if (nexttoken.equalsignorecase("stringtocount"))    count++; } 

and here's how find(i want find it's line):

int linen = 1; //set 1 loop return correct line number scanner scanner = new scanner("example.xml"); while (scanner.hasnextline()) {     linenum++;     if("stringtofind".equals(scanner.nextline().trim())) {          system.out.println("found on line: "+linenum);     } } 

i thought looking stringtofind, getting it's line number , making first scanner count stringtocount till line programming skills aren't enough sadly. question is, since have code only one of things want do, how combine these?

you use 2 if-statements in loop.

boolean foundstring = false; int count = 0, linenum = 1; while(scanner.hasnextline()){     string line = scanner.nextline();     if(line.equals("stringtofind")){         foundstring = true;         break; // break out of loop     }     else if(line.equals("stringtocount")) count++;     linenum++; } // code uses "foundstring" and/or "linenum" 

this code count number of lines match "stringtocount" until finds line matches "stringtofind" or files has no more un-read lines (linenum contain line number on occurred).


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -