Java Reference
In-Depth Information
Try It Out Counting Occurrences of Substrings
In this example, you look at how to use the “start character position” parameter of indexOf() . Here
you will count how many times the word Wrox appears in the string.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 5: Example 1</title>
</head>
<body>
<script type=”text/javascript”>
var myString = “Welcome to Wrox books. “;
myString = myString + “The Wrox website is www.wrox.com. “;
myString = myString + “Visit the Wrox website today. Thanks for buying Wrox”;
var foundAtPosition = 0;
var wroxCount = 0;
while (foundAtPosition != -1)
{
foundAtPosition = myString.indexOf(“Wrox”,foundAtPosition);
if (foundAtPosition != -1)
{
wroxCount++;
foundAtPosition++;
}
}
document.write(“There are “ + wroxCount + “ occurrences of the word Wrox”);
</script>
</body>
</html>
Save this example as ch5_examp1.htm . When you load the page into your browser, you should see the
following sentence: There are 4 occurrences of the word Wrox.
At the top of the script block, you built up a string inside the variable myString, which you then want
to search for the occurrence of the word Wrox. You also defi ne two variables: wroxCount will contain
the number of times Wrox is found in the string, and foundAtPosition will contain the position in the
string of the current occurrence of the substring Wrox.
You then used a while loop, which continues looping all the while you are fi nding the word Wrox in
the string — that is, while the variable foundAtPosition is not equal to -1 . Inside the while loop, you
have this line:
foundAtPosition = myString.indexOf(“Wrox”,foundAtPosition);
Here you search for the next occurrence of the substring Wrox in the string myString. How do you make
sure that you get the next occurrence? You use the variable foundAtPosition to give you the starting
position of your search, because this contains the index after the index position of the last occurrence
of the substring Wrox. You assign the variable foundAtPosition to the result of your search, the index
position of the next occurrence of the substring Wrox.
Search WWH ::




Custom Search