38
Visual Basic 2005 Visual Basic 2005 III. STRINGS, CHARACTERS AND REGULAR EXPRESSIONS MELJUN CORTES MELJUN CORTES

MELJUN CORTES

Embed Size (px)

Citation preview

Page 1: MELJUN CORTES

Visual Basic 2005Visual Basic 2005III. STRINGS, CHARACTERS AND REGULAR

EXPRESSIONS

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES

Strings, Characters and Regular Strings, Characters and Regular ExpressionsExpressionsObjectives

In this chapter you will learn:•To create and manipulate immutable character String objects of class String.•To create and manipulate mutable character String objects of class StringBuilder.•To manipulate character objects of structure Char.•To use regular expressions in conjunction with classes Regex and Match.

Visual Basic 20052

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS

Page 3: MELJUN CORTES

Fundamentals of Characters and Fundamentals of Characters and StringsStrings

Characters are the fundamental building blocks of Visual Basic source code

Every program is composed of characters that, when grouped together meaningfully, create a sequence that the compiler interprets as instructions

a program also can contain character literals, also called character constants

A character literal is a character that is represented internally as an integer value, called a character code

Visual Basic 2005

Strings, Characters and Regular Expressions

3STRINGS, CHARACTERS AND REGULAR EXPRESSIONS

Page 4: MELJUN CORTES

Fundamentals of Characters and Fundamentals of Characters and StringsStrings

Character literals are established according to the Unicode character set

A string is a series of characters treated as a single unit

A string is an object of class String in the System namespace

Visual Basic 2005

Strings, Characters and Regular Expressions

4STRINGS, CHARACTERS AND REGULAR EXPRESSIONS

Page 5: MELJUN CORTES

Fundamentals of Characters and Fundamentals of Characters and StringsStrings

We write string literals as sequences of characters in double quotation marks:

A declaration can assign a String literal to a String variable:

Dim color As String = “Blue”

“Gerick Andrei M. Salalima" “257-G Teresa St." “Sta. Mesa, Manila" "(632) 4689900"

Visual Basic 2005

Strings, Characters and Regular Expressions

5STRINGS, CHARACTERS AND REGULAR EXPRESSIONS

Page 6: MELJUN CORTES

String ConstructorsString Constructors

Class String provides constructors for initializing Strings

' string initialization originalString = "Welcome to VB programming!" string1 = originalString string2 = New String(characterArray) string3 = New String(characterArray, 6, 3) string4 = New String("C"c, 5)

Visual Basic 2005

Strings, Characters and Regular Expressions

6STRINGS, CHARACTERS AND REGULAR EXPRESSIONS

Page 7: MELJUN CORTES

String ConstructorsString Constructors

Sample program

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 7

Visual Basic 2005

Strings, Characters and Regular Expressions

‘Demonstrating String class constructorsModule StringConstructor Sub Main() Dim originalString, string1, string2, _ string3, string4 As String Dim characterArray() As Char = _ {"b"c, "i"c, "r"c, "t"c, "h"c, " "c, "d"c, "a"c, "y"c}

' string initialization originalString = "Welcome to VB programming!" string1 = originalString string2 = New String(characterArray) string3 = New String(characterArray, 6, 3) string4 = New String("C"c, 5) Console.WriteLine("string1 = " & """" & string1 & _ """" & vbCrLf & "string2 = " & """" & string2 & _ """" & vbCrLf & "string3 = " & """" & string3 & _ """" & vbCrLf & "string4 = " & """" & string4 & _ """" & vbCrLf) End Sub ' Main End Module ' StringConstructor

Page 8: MELJUN CORTES

String ConstructorsString Constructors

Output

Visual Basic 2005

Strings, Characters and Regular Expressions

8STRINGS, CHARACTERS AND REGULAR EXPRESSIONS

string1 = "Welcome to VB programming!" string2 = "birth day" string3 = "day" string4 = "CCCCC"

Page 9: MELJUN CORTES

StringString Indexer, Indexer, LengthLength Property and Property and CopyToCopyTo Method Method

The String indexer is used to access individual characters in a String

The property Length returns the length of the String

The CopyTo method copies a specified number of characters from a String into a Char array

Visual Basic 2005

Strings, Characters and Regular Expressions

9STRINGS, CHARACTERS AND REGULAR EXPRESSIONS

Page 10: MELJUN CORTES

StringString Indexer, Indexer, LengthLength Property and Property and CopyToCopyTo Method Method

Using the indexer, property Length and method CopyTo

Visual Basic 2005

Strings, Characters and Regular Expressions

10STRINGS, CHARACTERS AND REGULAR EXPRESSIONS

Dim string1 As String = “Hello there”Dim i As Integer

For i = string1.Length - 1 To 0 Step -1 Console.Write(string1(i)) Next i

Dim len As Integer

len = string1.Length

Dim characterArray() As Char

' copy characters from string1 into characterArraystring1.CopyTo(0, characterArray, 0, 5)

Page 11: MELJUN CORTES

Comparing StringsComparing Strings

Comparing Strings with = and String Methods Equals and CompareTo

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 11

' test for equality with = If string1 = "hello” Then Console.WriteLine("string1 equals ""hello""") End If

' test for equality using Equals methodIf string1.Equals("hello") Then Console.WriteLine("string1 equals ""hello""") End If

' test CompareToIf string1.CompareTo("hello") = 0 Then Console.WriteLine("string1 equals ""hello""") Else Console.WriteLine("string1 not equal to ""hello""")End If

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 12: MELJUN CORTES

Locating Characters and Substrings in Locating Characters and Substrings in StringStringss

In many applications, it is necessary to search for a character or set of characters in a String

For example, a programmer creating a word processor would want to provide capabilities for searching through documents

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 12

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 13: MELJUN CORTES

Locating Characters and Substrings in Locating Characters and Substrings in StringStringss

Searching for characters and substrings in Strings

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 13

Dim letters As String = "abcdefghijklmabcdefghijklm“Dim searchLetters As Char () = {"c"c, "a"c, "$"c}Dim index As Integer

index = letters.IndexOf("c"c) ‘this returns 2. . .index = letters.IndexOf("a"c, 1) ‘this returns 13. . .index = letters.IndexOf("$"c, 3, 5) ‘this returns -1

Character to be located

Starting index where search begins

No of characters to seek

IndexOf retruns the index of the first occurrence of the

character in the string

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 14: MELJUN CORTES

Locating Characters and Substrings in Locating Characters and Substrings in StringStringss

Searching for characters and substrings in Strings

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 14

Dim letters As String = "abcdefghijklmabcdefghijklm“Dim searchLetters As Char () = {"c"c, "a"c, "$"c}Dim index As Integer

index = letters.LastIndexOf("c"c) ‘this returns 15. . .index = letters.LastIndexOf("a"c, 25) ‘this returns 13. . .index = letters.LastIndexOf("$"c, 15, 5) ‘this returns -1

Character to be located

Starting index where search begins

No of characters to seek

LastIndexOf retruns the index of the last occurrence of the character in the string

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 15: MELJUN CORTES

Locating Characters and Substrings in Locating Characters and Substrings in StringStringss

Searching for characters and substrings in Strings

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 15

Dim letters As String = "abcdefghijklmabcdefghijklm“Dim searchLetters As Char () = {"c"c, "a"c, "$"c}Dim index As Integer

index = letters.IndexOfAny(searchLetters) ‘this returns 0. . .index = letters.IndexOfAny(searchLetters, 7) ‘this returns 13. . .index = letters.IndexOfAny(searchLetters, 7, 5) ‘this returns -1

IndexOfAny retruns the index of the first occurrence in the string of any character

in a specified array of unicode characters

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 16: MELJUN CORTES

Locating Characters and Substrings in Locating Characters and Substrings in StringStringss

Searching for characters and substrings in Strings

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 16

Dim letters As String = "abcdefghijklmabcdefghijklm“Dim searchLetters As Char () = {"c"c, "a"c, "$"c}Dim index As Integer

index = letters.LastIndexOfAny(searchLetters) ‘this returns 15. . .index = letters.LastIndexOfAny(searchLetters, 1) ‘this returns 0. . .index = letters.LastIndexOfAny(searchLetters, 25, 5)‘this returns -1

LastIndexOfAny retruns the index of the last occurrence in the string of any character

in a specified array of unicode characters

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 17: MELJUN CORTES

Extracting Substrings From Extracting Substrings From StringStringss

Class String provides two Substring methods, which are used to create a new String by copying part of an existing String

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 17

Dim letters As String = "abcdefghijklmabcdefghijklm“Dim output As String = “”

output = letters.Substring(20) ‘output gets hijklm. . .output = letters.Substring(0, 6) ‘output gets abcdef. . .

Starting index No of characters to extract from starting index

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 18: MELJUN CORTES

Concatenating Concatenating StringStringss

Like the & operator, the String class's Shared method Concat can be used to concatenate two Strings

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 18

Dim string1 As String = “Visual “Dim string2 As String = “Basic”Dim newString As String

newString = String.Concat(string1, string2) ‘newString gets Visual Basic. . .

Concat method

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 19: MELJUN CORTES

Miscellaneous Miscellaneous StringString Methods Methods

Class String provides several methods that return modified copies of Strings

String methods Replace, ToLower, ToUpper and Trim:

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 19

Dim string1 As String = “cheers!“Dim string2 As String = “GOOD BYE ”Dim string3 As String = “ spaces “Dim output As String

output = string1.Replace(“e”c, “E”c) ‘output gets “chEErs!”. . .output = string1.ToUpper() ‘output gets “CHEERS!”. . .output = string2.ToLower() ‘output gets “good bye” . . .output = string3.Trim() ‘output gets “spaces”. . .

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 20: MELJUN CORTES

Class Class StringBuilderStringBuilder

Objects of class String are constant strings, whereas object of class StringBuilder are mutable sequences of characters

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 20

' Demonstrating StringBuilder class constructors. Imports System.Text

Module StringBuilderConstructor Sub Main() Dim buffer1, buffer2, buffer3 As StringBuilder

buffer1 = New StringBuilder() buffer2 = New StringBuilder(10) buffer3 = New StringBuilder("hello") Console.WriteLine("buffer1 = """ & buffer1.ToString() & """") Console.WriteLine("buffer2 = """ & buffer2.ToString() & """") Console.WriteLine("buffer3 = """ & buffer3.ToString() & """") End Sub ' Main End Module ' StringBuilderConstructor

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 21: MELJUN CORTES

LengthLength and and CapacityCapacity Properties, Properties, EnsureCapacityEnsureCapacity Method and Indexer of Class Method and Indexer of Class StringBuilderStringBuilder

Class StringBuilder provides the Length and Capacity properties to return the number of characters currently in a StringBuilder and the number of characters that a StringBuilder can store without allocating more memory, respectively

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 21

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 22: MELJUN CORTES

LengthLength and and CapacityCapacity Properties, Properties, EnsureCapacityEnsureCapacity Method and Indexer of Class Method and Indexer of Class StringBuilderStringBuilder

StringBuilder size manipulation

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 22

Dim buffer As New StringBuilder("Hello, how are you?")

Console.WriteLine(buffer.ToString())Console.WriteLine(“Length = “ & buffer.Length)Console.WriteLine(“Capacity = “ & buffer.Capacity)

buffer.EnsureCapacity(75)Buffer.Length = 10

Console.WriteLine(buffer.ToString())

Hello, how are you?Length = 19Capacity = 32Hello, how

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 23: MELJUN CORTES

AppendAppend and and AppendFormatAppendFormat Methods of Methods of Class Class StringBuilderStringBuilder

Class StringBuilder provides 19 overloaded Append methods for appending values of various types to the end of a StringBuilder's contents

There are versions of this method for each of the primitive types and for character arrays, Strings and Objects

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 23

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 24: MELJUN CORTES

AppendAppend and and AppendFormatAppendFormat Methods of Methods of Class Class StringBuilderStringBuilder

Append methods of StringBuilder

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 24

Dim objectValue As Object = "hello“ Dim stringValue As String = "good bye“ Dim characterArray As Char() = {"a"c, "b"c, "c"c, "d"c, "e"c, "f"c} Dim booleanValue As Boolean = True Dim characterValue As Char = "Z"c Dim integerValue As Integer = 7 Dim longValue As Long = 1000000 Dim floatValue As Single = 2.5F ' F indicates that 2.5 is a float Dim doubleValue As Double = 33.333 Dim buffer As New StringBuilder()

' use method Append to append values to buffer buffer.Append(objectValue) buffer.Append(" ") buffer.Append(stringValue) buffer.Append(" ") buffer.Append(characterArray) buffer.Append(" “)buffer.Append(integerValue). . .

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 25: MELJUN CORTES

InsertInsert, , RemoveRemove and and ReplaceReplace Methods of Methods of Class Class StringBuilderStringBuilder

Class StringBuilder provides 18 overloaded Insert methods to allow values of various types to be inserted at any position in a StringBuilder

There are versions of Insert for each of the primitive types and for character arrays, Strings and Objects

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 25

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 26: MELJUN CORTES

InsertInsert, , RemoveRemove and and ReplaceReplace Methods of Methods of Class Class StringBuilderStringBuilder

StringBuilder text insertion and removal

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 26

Dim buffer As New StringBuilder("Hello, how are you?")

Console.WriteLine(buffer.ToString())buffer.Insert(18, " Gerick")Console.WriteLine(buffer.ToString())buffer.Replace(“Gerick", “Rainne")Console.WriteLine(buffer.ToString())buffer.Remove(18, 7)Console.WriteLine(buffer.ToString())

Hello, how are you?Hello, how are you Gerick?Hello, how are you Rainne?Hello, how are you?

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 27: MELJUN CORTES

CharChar Methods Methods

Many of the primitive types that we have used are actually aliases for different structures

For instance, an Integer is defined by structure System.Int32, a Long by System.Int64 and so on

Char, is the structure for charactersMost Char methods are Shared

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 27

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 28: MELJUN CORTES

CharChar Methods Methods

Char's Shared character-testing and case-conversion methods

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 28

Dim character As Char = “A”cDim output As String

output = "is digit: " & Char.IsDigit(character) & vbCrLf output &= "is letter: " & Char.IsLetter(character) & vbCrLf output &= "is letter or digit: " & _ Char.IsLetterOrDigit(character) & vbCrLf output &= "is lowercase: " & Char.IsLower(character) & vbCrLf output &= "is uppercase: " & Char.IsUpper(character) & vbCrLf output &= "to uppercase: " & Char.ToUpper(character) & vbCrLf output &= "to lowercase: " & Char.ToLower(character) & vbCrLf output &= "is punctuation: " & _ Char.IsPunctuation(character) & vbCrLf output &= "is symbol: " & Char.IsSymbol(character)

Console.WriteLine(output)

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 29: MELJUN CORTES

CharChar Methods Methods

Char's Shared character-testing and case-conversion methods

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 29

is digit: Falseis letter: Trueis letter or digit: Trueis lowercase: Falseis uppercase: Trueto uppercase: Ato lowercase: ais punctuation: Falseis symbol: False

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 30: MELJUN CORTES

Regular Expressions and Class Regular Expressions and Class RegExRegEx

Regular expressions are specially formatted Strings used to find (and possibly replace) patterns in text

They can be useful during information validation, to ensure that data is in a particular format

For example, a Philippine ZIP code must consist of four digits, and a last name must start with a capital letter

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 30

Visual Basic 2005

Strings, Characters and Regular Expressions

Page 31: MELJUN CORTES

Regular Expressions and Class Regular Expressions and Class RegExRegEx

Regular expression character classes:

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 31

Visual Basic 2005

Character class Matches Character class Matches

\d Any digit \D Any non-digit

\w Any word character \W Any non-word character

\s Any whitespace \S Any non-whitespace

Strings, Characters and Regular Expressions

Page 32: MELJUN CORTES

Regular Expressions and Class Regular Expressions and Class RegExRegEx

Regular expressions checking birthdays

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 32

Visual Basic 2005

‘ Demonstrating Class Regex. Imports System.Text.RegularExpressions

Module RegexMatches Sub Main() ' create regular expression Dim expression As New Regex("J.*\d[0-35-9]-\d\d-\d\d") Dim string1 As String = _ "Jane's Birthday is 05-12-75" & vbCrLf & _ "Dave's Birthday is 11-04-68" & vbCrLf & _ "John's Birthday is 04-28-73" & vbCrLf & _ "Joe's Birthday is 12-17-77"

' match regular expression to string and ' print out all matches For Each myMatch As Match In expression.Matches(string1) Console.WriteLine(myMatch) Next myMatch End Sub ' Main End Module ' RegexMatches

Strings, Characters and Regular Expressions

Page 33: MELJUN CORTES

Regular Expressions and Class Regular Expressions and Class RegExRegEx

Quantifiers used in regular expressions

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 33

Visual Basic 2005

Quantifier Matches

* Matches zero or more occurrences of the preceding pattern.

+ Matches one or more occurrences of the preceding pattern.

? Matches zero or one occurrences of the preceding pattern.

{n} Matches exactly n occurrences of the preceding pattern.

{n,} Matches at least n occurrences of the preceding pattern.

{n,m} Matches between n and m (inclusive) occurrences of the preceding pattern.

Strings, Characters and Regular Expressions

Page 34: MELJUN CORTES

Regular Expressions and Class Regular Expressions and Class RegExRegEx

Validating user information using regular expressions

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 34

Visual Basic 2005

Dim strLastName As String = "Salalima"

If Regex.Match(strLastName, "^[A-Z][a-zA-Z]*$").Success Then MessageBox.Show("Valid last name", "Message", _ MessageBoxButtons.OK, MessageBoxIcon.Information)Else MessageBox.Show("Invalid last name", "Message", _ MessageBoxButtons.OK, MessageBoxIcon.Error)End If

Strings, Characters and Regular Expressions

Page 35: MELJUN CORTES

Regular Expressions and Class Regular Expressions and Class RegExRegEx

Validating user information using regular expressions

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 35

Visual Basic 2005

Dim strAddress As String = "257-G Teresa St."

If Regex.Match(strAddress, _ "^[0-9]+\s+([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success Then MessageBox.Show("Valid address", "Message", _ MessageBoxButtons.OK, MessageBoxIcon.Information)Else MessageBox.Show("Invalid address", "Message", _ MessageBoxButtons.OK, MessageBoxIcon.Error)End If

Strings, Characters and Regular Expressions

Page 36: MELJUN CORTES

Regular Expressions and Class Regular Expressions and Class RegExRegEx

Validating user information using regular expressions

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 36

Visual Basic 2005

Dim strZip As String = "12345"

If Regex.Match(strZip, "^\d{5}$").Success Then MessageBox.Show("Valid zip code", "Message", _ MessageBoxButtons.OK, MessageBoxIcon.Information)Else MessageBox.Show("Invalid zip code", "Message", _ MessageBoxButtons.OK, MessageBoxIcon.Error)End If

Strings, Characters and Regular Expressions

Page 37: MELJUN CORTES

ExerciseExerciseSTRINGS, CHARACTERS AND REGULAR EXPRESSIONS 37

Visual Basic 2005

Page 38: MELJUN CORTES

End of Strings, Characters and End of Strings, Characters and Regular ExpressionsRegular Expressions

STRINGS, CHARACTERS AND REGULAR EXPRESSIONS 38

Visual Basic 2005