1 visual basic strings: left$, mid, replace files: reading and writing

49
1 Visual Basic Strings: Left$, Mid, Replace Files: Reading and Writing

Upload: aldous-daniels

Post on 03-Jan-2016

231 views

Category:

Documents


4 download

TRANSCRIPT

1

Visual Basic

Strings: Left$, Mid, Replace

Files: Reading and Writing

2

Len

The function Len takes a string in as an argument and returns the length of the string, i.e. the number of characters in the string

e.g. Len(“cataloging”) 10 P. 311 in Deitel, Deitel and Nieto

3

The Left$ string function

Left$ takes two parameters – The first: a string– The second: an integer

It returns a string, which contains the same characters as the leftmost part of the string parameter and the length of which is given by the second parameter

There’s a corresponding Right$ function e.g. Left(“cataloging”,3) “cat” P. 312 in Deitel, Deitel and Niteo

4

Example: UserName Constructor

5

Example: UserName Constructor

6

UserName Constructor (Code)

Private Sub cmdOK_Click() Dim UserName As String Dim FirstName As String Dim LastName As String FirstName = LCase$(txtFirstName.Text) ‘Lower Case LastName = LCase$(txtLastName.Text) UserName = Left$(LastName, 6) ‘up to 6 chars UserName = UserName & Left$(FirstName, 1) ‘concatenate UserName = UserName & 1 lblUserName.Caption = "Your username is: " & UserNameEnd Sub

Note: O’Neill, O’Hanlon, etc

7

Mid

Takes two or three arguments– A string– Two integers (the starting position and the {optional} length)

It creates a string (of length given by the second integer parameter) by taking characters from the string beginning with the starting position (first integer parameter) {if second integer missing then all remaining chars}

Mid(“cataloging”,5,3) “log” Mid(“cataloging”, 5) “loging” p. 311 in Deitel, Deitel and Nieto

8

InStr

Takes two or three arguments– An optional integer (the starting position)– Two strings

Looks for the second string within the first and returns the position of the first occurrence or a 0 if the string is not found (strings positions start counting at 1)

Instr(“cataloging”, ”log”) 5 Instr(6, “cataloging”, ”log”) 0 p. 313 in Deitel, Deitel and Nieto

9

Replace

Has three or four arguments– Three strings – An optional integer (the starting position)

Replaces occurrences of second string found in first string with third string starting at the starting position if provided, the beginning otherwise

Replace(“aardvark”,”aa”,”a”) “ardvark” Replace(“aaardvark”,”aa”,”a”) “aardvark” Replace(“O’Hanlon”,”’”,””) “OHanlon” P. 319 in Deitel, Deitel and Nieto

10

Chr and Asc

Chr takes in a number corresponding to the ASCII value for a character and returns the character

Chr(66) “B” Chr(34) “ Asc takes in a string corresponding to a single

character and returns the ASCII value Asc(“C”) 67 P. 321 in Deitel, Deitel and Nieto

11

ASCII

ASCII (Number) Symbol

00110000 48 0

00110001 49 1

01000001 65 A

01000010 66 B

01100001 97 a

12

Example: EncryptionCaesar shift substitution cipher

13

Example: Encryption (Code)

Private Sub cmdEncrypt_Click() Dim i As Integer Dim Letter As String Dim Message As String Message = txtMessage.Text txtEncrypted.Text = "“

For i = 1 To Len(Message) ‘Len gives length of string Letter = Mid(Message, i, 1) ‘grabs a single letter txtEncrypted.Text = txtEncrypted.Text & Chr(Asc(Letter) + 1) Next iEnd Sub

‘Note: unlike arrays, strings start at 1

shift

14

CookieA Persistence Example

A cookie (sometimes known as a persistence cookie) is a file placed on a user’s computer by a web server that stores information about the user’s having visited and used a web site– It might store various custom settings, which

hyperlinks have been clicked, and so on

15

Persistence

An object (program) is said to have persistence if it stores and recalls data from previous executions

The data is not stored in the program file but in a separate file

16

The persistence of memory

Storage

17

Object Oriented Files

There is more to a file than just a pointer indicating its location. A file – Has a name and location – May exist or not exist– May be read/write or read only– May be in use by another user– Etc.

The above contribute to the properties and methods of an object oriented file

18

File System Object

The first step in accessing a file in VB is to instantiate a new FileSystemObject

The FileSystemObject contains a whole hierarchy of information about a file, e.g. the drive it’s on, folder it’s in, etc. – One can gather information on, as well as create,

delete and change files and folders

19

Reference

Strictly speaking the FileSystemObject is not a part of VB but of the Scripting Runtime library, therefore one needs to reference the Scripting Runtime library

– A reference is a way to expand VB’s namespace – that is, introduce new “key words”

– See View, Object Browser

Go to Project/References Scroll down and select (check) Microsoft Scripting

Runtime

20

Simple text files

The FileSystemObject allows one to deal with a file as a simple text (Strings) file, e.g. – Read a line, read the next line, and so on– Write a line, write the next line, and so on

The ultimate passing strings back and forth (reading and writing) is done by the TextStream Object

21

Other files

Random-access files (which allow a non-sequential access to the data) and application files like Word’s doc and Excel’s xls (which contain formatting information in addition to data) are accessed in a different way

22

Ignoring the middle ground

In between the FileSystemObject and the TextStream are the Folder Objects and the File Objects

If one does not need specific information about the folders and files but simple wants to read and write, one can go directly from FileSystemObject to TextStream

23

Declare vs Instantiate

Dim tsStreamMessage as TextStream– Declares a “pointer” that can point to a TextStream object, the

object (methods and properties associated with TextStream are not copied to memory, yet.

Dim fso as new FileSystemObject– This declares and instantiates

Dim o as SomeObject ‘declare

Set o = new SomeObject ‘instantiate

24

Example: Writing to a text file

25

Example: Writing to a text file

26

Example: Writing to a text file

Option ExplicitDim fsoMessageFile As New FileSystemObject ‘declare and instantiateDim tsTextMessage As TextStream ‘declareDim Message As String

Private Sub Form_Load() Dim fileName as String fileName = App.Path & "\message.txt", Set tsTextMessage = fsoMessageFile.OpenTextFile( fileName, ForWriting, True)End Sub

Private Sub cmdSend_Click() Message = txtMessage.Text tsTextMessage.Write (Message)End Sub

Path and file name

Read, write or append

Create if it doesn’t exist

27

Writing versus Appending

In the previous program the TextStream was created for writing, if the program is run again, causing the file to be reopened, the second message overwrites the first

Note that this is different from writing more before the program ends (the file was only opened once)

28

Writing a second time

29

Writing a second time

30

Appending Instead

31

Appending Instead

Option ExplicitDim fsoMessageFile As New FileSystemObjectDim tsTextMessage As TextStreamDim Message As String

Private Sub Form_Load() Dim fileName as String fileName = App.Path & "\message.txt" Set tsTextMessage = fsoMessageFile.OpenTextFile(fileName, forAppending, True)End Sub

Private Sub cmdSend_Click() Message = txtMessage.Text tsTextMessage.Write (Message)End Sub

Still use write here

32

Example: Reading from a file

33

Example: Reading from a file

34

Example: Reading from a file

Option ExplicitDim fsoFileToRead As New FileSystemObjectDim foFileToRead As FileDim tsMessageRead As TextStream

Private Sub Form_Load() Set foFileToRead = fsoFileToRead.GetFile(App.Path & _ "\

message2.txt") Set tsMessageRead = foFileToRead.OpenAsTextStreamEnd Sub

‘going through File object instead of directly to TextStream

35

Reading (Cont.)

Private Sub cmdRead_Click() txtMessage.Text = tsMessageRead.ReadAllEnd Sub

Reads entire contents of file at once

36

Text to be read line-by-line

37

Reading line-by-line

38

Reaching the end

39

Reading line-by-line (part 1)

Option Explicit

Dim fsoMyFile As New FileSystemObjectDim foMyFile As FileDim tsMyText As TextStream

Private Sub Form_Load() Set foMyFile = fsoMyFile.GetFile(App.Path & "\

message3.txt") Set tsMyText = foMyFile.OpenAsTextStreamEnd Sub

40

Reading line-by-line (part 2)

Private Sub cmdNext_Click() If Not tsMyText.AtEndOfStream Then txtMessage.Text = tsMyText.ReadLine Else txtMessage.Text = "THE END" cmdNext.Enabled = False End IfEnd Sub

Asks whether the end has been reached

41

Excel to Comma-separated file

42

File/Save As CSV

43

Viewed in Notepad

44

Parsing

One place in which strings and files come together is when the information read in has to be “parsed”

“In linguistics, to divide language into small components that can be analyzed. For example, parsing this sentence would involve dividing it into words and phrases and identifying the type of each component (e.g., verb, adjective, or noun). “

(http://www.webopedia.com)

45

Parsing and Tokens

In order for a computer to understand code, the code must be “parsed”

The first stage of parsing is to break the code down into “tokens”

A token is a single element of a programming language.

For example, a token could be a keyword, variable, or operator symbol

46

Delimiter

In programming, a delimiter is a character that identifies the beginning or the end of token (string)

The delimiting character is not part of the token. A space or a backslash (\) or a forward slash (/) is

often a delimiter What delimiters are used depends on the rules of

the language The interpreter must know what the delimiters are. “White spaces” = space, tab, return are examples

of delimiters

47

Delimiters in databases

Delimiters can also be used to separate the database fields (the columns in the database table) when transporting the database to another application.

For example, a comma-separated values (CSV) file is one way to separate the value in a cell from that in the next cell. The beginning of a row is indicated by a new line character.

48

Tokenizer Logic

Replace all optional delimiters with one default delimiter (for example, if there were semicolons and commas)

Eliminate any occurrences of two or more default delimiters appearing in a row

– Replace occurrences of two delimiters with one delimiter, repeat until length of string is unchanged

Find location of first delimiter and split the string into a token and the remainder of the string, repeat until the no more delimiters are found

You may need to add a delimiter to the end of the string so that the last token can be found

49

Do…Loop While

‘makes replacements of two spaces with one ‘space until no new string generated

Const TWO_SPACES = “ “ Const SPACE_D = “ “ Do Text1 = Text ‘copy original Text = Replace(Text, TWO_SPACES, SPACE_D) Loop While Text1 <> Text ‘has copy changed