19.04.2017 Views

Learn to Program with Small Basic

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

5 TextWindow.WriteLine(str)<br />

6 TextWindow.WriteLine("This file has " + len + " characters.")<br />

Listing 19-1: Demonstrating the ReadContents() method<br />

This<br />

is a<br />

Here is the output of this program:<br />

Test.<br />

This file has 19 characters.<br />

Line 2 sets the file’s absolute path. Line 3 reads the entire contents of<br />

the file and saves the returned string in a variable named str using the<br />

ReadContents() method. ReadContents() takes one argument: the pathname of<br />

the file you want <strong>to</strong> read. Line 4 gets the length of the string and saves it in<br />

a variable named len. Lines 5–6 display the str and len variables.<br />

But why does GetLength() output 19 characters for the string’s length<br />

when the string "This is a Test." contains only 15? To understand what’s<br />

going on, you need <strong>to</strong> examine the actual characters that make up the<br />

str variable. Remember from Chapter 18 that characters are encoded in a<br />

format (such as ASCII or Unicode). Add the following code <strong>to</strong> the end of<br />

Listing 19-1, and run the program again:<br />

For N = 1 To len<br />

ch = Text.GetSubText(str, N, 1) ' Gets one character<br />

code = Text.GetCharacterCode(ch) ' Gets the code for this character<br />

TextWindow.WriteLine(code) ' Displays it<br />

EndFor<br />

This code shows that the str variable has 19 characters. Figure 19-4<br />

breaks down what the program is doing.<br />

Code<br />

84 104 105 115 13 10 105 115 32 97 13 10 13 10 84 101 115 116 46<br />

Character<br />

T<br />

h i s i s a t e s t .<br />

Carriage return<br />

Line feed<br />

Space<br />

Carriage return<br />

Line feed<br />

Carriage return<br />

Line feed<br />

Figure 19-4: The 19 characters of the str variable in Listing 19-1<br />

Notepad inserts two special characters (called carriage return and line<br />

feed, whose ASCII codes are 13 and 10) <strong>to</strong> mark the end of each line. Think<br />

of the newline (or end-of-line) marker as a pair of characters produced<br />

when you press enter on the keyboard. Without these characters, the lines<br />

292 Chapter 19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!