Wednesday, April 18, 2007

 

Counting patterns in a string (Ch. 11)

Once you are quite familiar with the basic string-handling tools of this chapter (see previous blog entry, and try "Extra Exercises"), you can expand your abilities.

Study carefully the section on Counting Patterns in a Word (p. 182), since it introduces a technique that you will apply in other, related situations. The idea is that, after you search for and find one pattern in a string, before searching again you REDEFINE THE WORD.

You redefine it so that the new word begins somewhere after the position where the first pattern started. For example, if the word was "mississippi" and the pattern was "iss," we would want the word to be redefined as "issippi." How do we do that? The new word will begin somewhere after position 2, where we found the first "iss," using index (word, pattern). But you don't want it to begin exactly AT position 2. You want it to begin at position 2 plus the length of the pattern, in our example the length of "iss." In otyher words, the redefined word begins at

word (index(word, pattern)) + length(pattern)

and it includes the remaining part of the word, namely,

..*)

Putting it all together we redefine the word as follows:

word := word (index(word, pattern) + length(pattern) .. *)



It's easier to understand if you follow the textbook and use a variable pos for the position of the pattern - in our example, iss - and a variable size for the length of the pattern. Your code looks much simpler if you use two variable like these:

pos : int := index (word, pattern)
size : int := length (pattern)

Thus the long, confusing line to redefine the word is much easier to understand when it's simplified to

word := word (pos + size ..*)



<< Home

This page is powered by Blogger. Isn't yours?