Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Visual Basic Strings: Left$, Mid, Replace Files: Reading and Writing."— Presentation transcript:

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

2 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 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 4 Example: UserName Constructor

5 5

6 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: " & UserName End Sub Note: O’Neill, O’Hanlon, etc

7 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 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 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 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 11 ASCII (Number)Symbol 00110000480 00110001491 0100000165A 0100001066B 0110000197a

12 12 Example: Encryption Caesar shift substitution cipher

13 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 i End Sub ‘Note: unlike arrays, strings start at 1 shift

14 14 Cookie A 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 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 16 The persistence of memory Storage

17 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 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 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 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 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 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 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 24 Example: Writing to a text file

25 25 Example: Writing to a text file

26 26 Example: Writing to a text file Option Explicit Dim fsoMessageFile As New FileSystemObject ‘declare and instantiate Dim tsTextMessage As TextStream ‘declare Dim 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 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 28 Writing a second time

29 29 Writing a second time

30 30 Appending Instead

31 31 Appending Instead Option Explicit Dim fsoMessageFile As New FileSystemObject Dim tsTextMessage As TextStream Dim 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 32 Example: Reading from a file

33 33 Example: Reading from a file

34 34 Example: Reading from a file Option Explicit Dim fsoFileToRead As New FileSystemObject Dim foFileToRead As File Dim tsMessageRead As TextStream Private Sub Form_Load() Set foFileToRead = fsoFileToRead.GetFile(App.Path & _ "\message2.txt") Set tsMessageRead = foFileToRead.OpenAsTextStream End Sub ‘going through File object instead of directly to TextStream

35 35 Reading (Cont.) Private Sub cmdRead_Click() txtMessage.Text = tsMessageRead.ReadAll End Sub Reads entire contents of file at once

36 36 Text to be read line-by-line

37 37 Reading line-by-line

38 38 Reaching the end

39 39 Reading line-by-line (part 1) Option Explicit Dim fsoMyFile As New FileSystemObject Dim foMyFile As File Dim tsMyText As TextStream Private Sub Form_Load() Set foMyFile = fsoMyFile.GetFile(App.Path & "\message3.txt") Set tsMyText = foMyFile.OpenAsTextStream End Sub

40 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 If End Sub Asks whether the end has been reached

41 41 Excel to Comma-separated file

42 42 File/Save As CSV

43 43 Viewed in Notepad

44 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 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 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 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 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 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


Download ppt "1 Visual Basic Strings: Left$, Mid, Replace Files: Reading and Writing."

Similar presentations


Ads by Google