Thursday, April 19, 2007

 

Substituting One Pattern for Another (Ch. 11)

Let's say you want to change the string "music" to "muzic".

The method Turing uses is to separate the first part, to just before the "s" for which you want to substitute a "z", add the "z", then add the rest of the string that followed the "s". In other words, like this:


You get the first part, "mu", by taking the string from postion 1 until index (string, pattern) minus 1. Again, as we did in the previous exercise, let's simplify by creating the variable pos : int := index (string, pattern). So separating the "mu" of "music" looks like this:

word (1 .. pos - 1

We add the "z" like this:

+ "z"

and we finish by adding the part of the string AFTER the "s" like this:

pos + 1 .. *


In summary, the complete line to substitute the "s" in "music" for a "z" is

word: = word ((1 .. pos -1) + "z" + (pos +1 .. *))


What do you do with the pieces of string!

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 ..*)

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