Java Reference
In-Depth Information
The extract function is not part of Java. It is a useful function that I developed to
help with string parsing. The extract function returns some text that is bounded by two token
strings. Now, let's take a look at how it works.
The extract function begins by declaring two int variables. Additionally the pa-
rameters token1 and token2 are passed in. The parameter token1 holds the text,
which is usually an HTML tag that occurs at the beginning of the desired text. The parameter
token2 holds the text, which is usually an HTML tag that occurs at the end of the desired
text.
int location1, location2;
location1 = location2 = 0;
These two variables will hold the location of the beginning and ending text. To begin with,
they are both set to zero. Next, the function will begin looking for instances of token1 .
This is done with a do/while loop.
do
{
location1 = str.indexOf(token1, location1);
if (location1 == -1)
return null;
As you can see location1 is set to the location of token1 . The search begins at
location1 . Since location1 begins with the value of zero, this search also begins at
the beginning of the string. If no instance of token1 is found, the null is returned to let
the caller know that the string could not be extracted.
Each time an instance of token1 is found, the variable count is decreased by one.
This is shown here:
count--;
} while (count > 0);
Once the final instance of token1 has been found, it is time to locate the ending token.
This is done with the following lines of code:
location2 = str.indexOf(token2, location1 + 1);
if (location2 == -1)
return null;
return str.substring(location1 + token1.length(),location2);
Search WWH ::




Custom Search