Question

I'm moving some code from objective-c to java. The project is an XML/HTML Parser. In objective c I pretty much only use the scanUpToString("mystring"); method.

I looked at the Java Scanner class, but it breaks everything into tokens. I don't want that. I just want to be able to scan up to occurrences of substrings and keep track of the scanners current location in the overall string.

Any help would be great thanks!

EDIT

to be more specific. I don't want Scanner to tokenize.

String test = "<title balh> blah <title> blah>";
    Scanner feedScanner = new Scanner(test);
    String title = "<title";
    String a = feedScanner.next(title);
    String b = feedScanner.next(title);

In the above code I'd like feedScanner.next(title); to scan up to the end of the next occurrence of "<title"

What actually happens is the first time feeScanner.next is called it works since the default delimiter is whitespace, however, the second time it is called it fails (for my purposes).

Was it helpful?

Solution

This really is easier by just using String's methodsdirectly:

String test = "<title balh> blah <title> blah>";
String target = "<title";
int index = 0;
index = test.indexOf( target, index ) + target.length();
// Index is now 6 (the space b/w "<title" and "blah"
index = test.indexOf( target, index ) + target.length();
// Index is now at the ">" in "<title> blah"

Depending on what you want to actually do besides walk through the string, different approaches might be better/worse. E.g. if you want to get the blah> blah string between the <title's, a Scanner is convenient:

String test = "<title balh> blah <title> blah>";
Scanner scan = new Scanner(test);
scan.useDelimiter("<title");
String stuff = scan.next(); // gets " blah> blah ";

OTHER TIPS

You can achieve this with String class (Java.lang.String).

  1. First get the first index of your substring.

    int first_occurence= string.indexOf(substring);

  2. Then iterate over entire string and get the next value of substrings

    int next_index=indexOf( str,fromIndex);

  3. If you want to save the values, add them to the wrapper class and the add to a arraylist object.

Maybe String.split is something for you?

s = "The almighty String is mystring is your String is our mystring-object - isn't it?";
parts = s.split ("mystring");

Result:

Array("The almighty String is ", " is your String is our ", -object - isn't it?)

You know that in between your "mystring" must be. I'm not sure for start and end, so maybe you need some s.startsWith ("mystring") / s.endsWith.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top