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

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

CC SQL Utilities.
Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.
Session 13 Active Server Pages (ASP) Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
CS1100: Computer Science and Its Applications Text Processing Created By Martin Schedlbauer
VBA Modules, Functions, Variables, and Constants
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Creating Web Page Forms
Games and Simulations O-O Programming in Java The Walker School
PHP : Hypertext Preprocessor
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
Tutorial 14 Working with Forms and Regular Expressions.
JavaScript, Fourth Edition
Lists in Python.
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
Miscellaneous Excel Combining Excel and Access. – Importing, exporting and linking Parsing and manipulating data. 1.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
Language Elements 1. Data Types 2 Floating Point (real) Single Precision Double Precision Decimal Fixed Point (integer) Byte Short Integer Long Numerical.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Chapter 8 Cookies And Security JavaScript, Third Edition.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
 Agenda: 4/24/13 o External Data o Discuss data manipulation tools and functions o Discuss data import and linking in Excel o Sorting Data o Date and.
Arrays Code: Arrays Controls: Control Arrays, PictureBox, Timer.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
1 Flow Control II Code: Select-Case and For-Next Controls: Frames and OptionButtons.
String Manipulation. Strings have their own properties and methods, just like a textbox or label or form does.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
I Power Higher Computing Software Development High Level Language Constructs.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
6-1 Chapter 6 Working with Arrays in VB.NET. 6-2 Learning Objectives Understand the use of list and table arrays in VB.NET projects and the difference.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Files Tutor: You will need ….
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
Processing Text Excel can not only be used to process numbers, but also text. This often involves taking apart (parsing) or putting together text values.
String Manipulation 10/21/2015 Lect#6 GC Strings have their own properties and methods, just like a textbox or label or form does. 10/21/2015 Lect#6.
PHP Form Processing * referenced from
1 Dynamic Arrays ListBoxes, Dynamic Arrays, Dynamic Control Arrays ListBoxes are on pp and dynamic arrays are in Chapter 7 of Deitel, Deitel and.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
FILE I/O: Low-level 1. The Big Picture 2 Low-Level, cont. Some files are mixed format that are not readable by high- level functions such as xlsread()
String Manipulation Reference:
Definition of the Programming Language CPRL
VBA - Excel VBA is Visual Basic for Applications
Chapter 6 JavaScript: Introduction to Scripting
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
Introduction to Scripting
Iteration, FileSystemObject and Multiple Forms
Chapter 3 Introduction to Classes, Objects Methods and Strings
WEB PROGRAMMING JavaScript.
String Manipulation Reference:
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
String Manipulation Reference:
Tonga Institute of Higher Education
Topic 6 Lesson 1 – Text Processing
Introduction to Computer Science
Presentation 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

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 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 (Number)Symbol A B a

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

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 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 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 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 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 Example: Reading from a file

33 Example: Reading from a file

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 Reading (Cont.) Private Sub cmdRead_Click() txtMessage.Text = tsMessageRead.ReadAll End 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 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 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 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). “ (

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