1 / 67

Chapter 15 – Strings, Characters and Regular Expressions

Chapter 15 – Strings, Characters and Regular Expressions.

magnar
Télécharger la présentation

Chapter 15 – Strings, Characters and Regular Expressions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 15 – Strings, Characters and Regular Expressions Outline15.1 Introduction15.2   Fundamentals of Characters and Strings15.3   String Constructors15.4   StringLength and Chars Properties and CopyTo Method15.5   Comparing Strings15.6   String Method GetHashCode15.7   Locating Characters and Substrings in Strings15.8   Extracting Substrings from Strings15.9   Concatenating Strings15.10   Miscellaneous String Methods15.11   ClassStringBuilder15.12   StringBuilder Indexer, Length and CapacityProperties, and EnsureCapacity Method15.13 StringBuilder Append and AppendFormat Methods 15.14StringBuilderInsert, Remove and Replace Methods15.15 Char Methods15.16Card Shuffling and Dealing Simulation15.17Regular Expressions and Class Regex

  2. 15.1 Introduction • String and character processing • Useful in a variety of applications • String and Char classes (System) • General string and character processing, storage • StringBuilder class (System.Text) • Facilitates efficient construction of strings • Regex and Match classes (System.Text.RegularExpressions) • Powerful pattern matching capabilities

  3. 15.2   Fundamentals of Characters and Strings • Characters • Fundamental building blocks of source code • Character constants • Represented using double quotes and c character • All characters correspond to an integer character code • Unicode character set • ChrW function converts Unicode values to characters

  4. 15.2   Fundamentals of Characters and Strings • Strings • A series of characters treated as a single unit • String literals • Objects of class String • Upcoming example: String constructors

  5. ChrW converts Unicode value 34 to double quote character, " Creates an array of type Char.Suffix c required when using OptionStrict Creates a literal String object Creates a new String object containing a copy of characters in characterArray string1 and originalString reference same literal String object Copies characters from characterArray, starting at the index indicated by second argument and continuing for the number of characters indicated by the third argument Creates a String with length indicated by the second argument, filled with copies of the character passed as the first argument Each instance of variable quotes represents a double quote character, " 1 ' Fig. 15.1: StringConstructor.vb 2 ' Demonstrating String class constructors. 3 4 Imports System.Windows.Forms 5 6 Module modStringConstructor 7 8 Sub Main() 9 Dim characterArray AsChar() 10 Dim output AsString 11Dim quotes AsString = ChrW(34) 12 Dim originalString, string1, string2, string3, _ 13 string4 AsString 14 15 characterArray = NewChar() {"b"c, "i"c, "r"c, _ 16 "t"c, "h"c, " "c, "d"c, "a"c, "y"c} 17 18 ' string initialization 19originalString ="Welcome to VB.NET Programming!" 20 string1 = originalString 21 string2 = New String(characterArray) 22 string3 = New String(characterArray, 6, 3) 23 string4 = New String("C"c, 5) 24 25 output = "string1 = " & quotes & string1 & quotes & _ 26 vbCrLf & "string2 = " & quotes & string2 & quotes & _ 27 vbCrLf & "string3 = " & quotes & string3 & quotes & _ 28 vbCrLf & "string4 = " & quotes & string4 & quotes 29 30 MessageBox.Show(output, "String Class Constructors", _ 31 MessageBoxButtons.OK, MessageBoxIcon.Information) 32 EndSub' Main 33 34 EndModule' modStringConstructor StringConstructor.vbChrW functionCalls to String constructors

  6. StringConstructor.vb

  7. Length property returns number of characters in string Copies characters from a string into an array.Respectively, arguments represent: the location at which to begin copying, the destination array, the index into which to place the first character copied and the number of characters to copy Length property used to loop backwards through characters in string1 Returns the character at the position indicated by the integer argument 1 ' Fig. 15.2: StringMiscellaneous.vb 2 ' Using properties Length and Chars 3 ' of class string. 4 5 Imports System.Windows.Forms 6 7 Module modMiscellaneous 8 9 Sub Main() 10 Dim string1, output AsString 11 Dim characterArray AsChar() 12 Dim i AsInteger 13 Dim quotes AsString = ChrW(34) 14 15 string1 = "hello there" 16 characterArray = NewChar(5) {} 17 18 ' output string 19 output = "string1: " & quotes & string1 & quotes 20 21 ' test Length property 22 output &= vbCrLf & "Length of string1: " & string1.Length 23 24 ' loop through characters in string1 and display 25 ' reversed 26 output &= vbCrLf & "The string reversed is: " 27 28For i = string1.Length - 1To0Step-1 29 output &= string1.Chars(i) 30 Next 31 32 ' copy characters from string1 into characterArray 33 string1.CopyTo(0, characterArray, 0, 5) 34 output &= vbCrLf & "The character array is: " 35 StringMiscellaneous.vb

  8. Displays contents of characterArray 36For i = 0To characterArray.Length - 1 37 output &= characterArray(i) 38 Next 39 40 MessageBox.Show(output, "Demonstrating String" & _ 41 " properties Length and Chars", _ 42 MessageBoxButtons.OK, MessageBoxIcon.Information) 43 EndSub' Main 44 45 EndModule' modMiscellaneous StringMiscellaneous.vb

  9. 15.5   Comparing Strings • Lexicographical comparison • Similar to alphabetization • Each character corresponds to a number • Character codes compared from beginning of string • Methods Equals, CompareTo and = operator • Reference comparison • Determines whether two references contain the same object • Isoperator • Upcoming example: String test to determine equality

  10. Method Equals performs case-sensitive lexicographical comparison Equality operator produces same results as method Equals 1 ' Fig. 15.3: StringCompare.vb 2 ' Comparing strings. 3 4 Imports System.Windows.Forms 5 6 Module modCompare 7 8 Sub Main() 9 Dim string1 AsString = "hello" 10 Dim string2 AsString = "good bye" 11 Dim string3 AsString = "Happy Birthday" 12 Dim string4 AsString = "happy birthday" 13 Dim output AsString 14 Dim quotes AsString = ChrW(34) 15 16 ' output values of four Strings 17 output = "string1 = " & quotes & string1 & quotes & _ 18 vbCrLf & "string2 = " & quotes & string2 & quotes& _ 19 vbCrLf & "string3 = " & quotes & string3 & quotes& _ 20 vbCrLf & "string4 = " & quotes & string4 & quotes& _ 21 vbCrLf & vbCrLf 22 23 ' test for equality using Equals method 24If (string1.Equals("hello")) Then 25 output &= "string1 equals " & quotes & "hello" & _ 26 quotes & vbCrLf 27 28 Else 29 output &= "string1 does not equal " & quotes & _ 30 "hello" & quotes & vbCrLf 31 EndIf 32 33 ' test for equality with = 34If string1 = "hello"Then 35 output &= "string1 equals " & quotes & "hello" & _ StringCompare.vbCall to Equals= operator

  11. Shared method Equals compares two Strings lexicographically Method CompareTo performs a lexicographical comparison.Returns 0 if Strings are equal.Returns –1 if argument String is greater.Returns 1 if calling String is greater 36 quotes & vbCrLf 37 Else 38 output &= "string1 does not equal " & quotes & _ 39 "hello" & quotes & vbCrLf 40 EndIf 41 42 ' test for equality comparing case 43If (String.Equals(string3, string4)) Then 44 output &= "string3 equals string4" & vbCrLf 45 Else 46 output &= "string3 does not equal string4" & vbCrLf 47 EndIf 48 49 ' test CompareTo 50 output &= vbCrLf & "string1.CompareTo(string2) is " & _ 51 string1.CompareTo(string2) & vbCrLf & _ 52 "string2.CompareTo(string1) is " & _ 53 string2.CompareTo(string1) & vbCrLf & _ 54 "string1.CompareTo(string1) is " & _ 55 string1.CompareTo(string1) & vbCrLf & _ 56 "string3.CompareTo(string4) is " & _ 57 string3.CompareTo(string4) & vbCrLf & _ 58 "string4.CompareTo(string3) is " & _ 59 string4.CompareTo(string3) & vbCrLf & vbCrLf 60 61 MessageBox.Show(output, "Demonstrating string" & _ 62 " comparisons", MessageBoxButtons.OK, _ 63 MessageBoxIcon.Information) 64 EndSub' Main 65 66 EndModule ' modCompare StringCompare.vbCall to EqualsCall to CompareTo

  12. StringCompare.vb

  13. Method StartsWith determines whether the beginning of a String matches the String passed as an argument Method EndsWith determines whether the end of a String matches the String passed as an argument 1 ' Fig. 15.4: StringStartEnd.vb 2 ' Demonstrating StartsWith and EndsWith methods. 3 4 Imports System.Windows.Forms 5 6 Module modStartEnd 7 8 Sub Main() 9 Dim strings AsString() 10 Dim output AsString = "" 11 Dim i AsInteger 12 Dim quotes AsString = ChrW(34) 13 14 strings = NewString() {"started", "starting", _ 15 "ended", "ending"} 16 17 ' test every string to see if it starts with "st" 18 For i = 0To strings.GetUpperBound(0) 19 20If strings(i).StartsWith("st") Then 21 output &= quotes & strings(i) &quotes & _ 22 " starts with " & quotes & "st" & quotes & vbCrLf 23 EndIf 24 25 Next 26 27 output &= vbCrLf 28 29 ' test every string to see if it ends with "ed" 30 For i = 0 To strings.GetUpperBound(0) 31 32If strings(i).EndsWith("ed") Then 33 output &= quotes & strings(i) & quotes & _ 34 " ends with " & quotes & "ed" & quotes & vbCrLf StringStartEnd.vbCall to StartsWithCall to EndsWith

  14. 35 EndIf 36 37 Next 38 39 MessageBox.Show(output, "Demonstrating StartsWith and" & _ 40 " EndsWith methods", MessageBoxButtons.OK, _ 41 MessageBoxIcon.Information) 42 EndSub ' Main 43 44 EndModule' modStartEnd StringStartEnd.vb

  15. 15.6   String Method GetHashCode • Hash tables • Store data so that it can be retrieved efficiently • Complex data types, such as Strings, can be used to look up data in hash table • Hash codes • Facilitate logical storage and retrieval of data items • Every possible data item corresponds to a number (hash code) • Code is obtained using a special calculation (hash function) • Produces identical hash codes for identical data • Should distribute data evenly among hash codes • Defined in Overridable method GetHashCode • Upcoming example: GetHashCode method demonstration

  16. Strings to be hashed differ only in case of first letter Calling GetHashCode on any String containing "hello" always produces hash code 178056679 Despite similarity, to "hello", "Hello" produces code 222703111 1 ' Fig. 15.5: StringHashCode.vb 2 ' Demonstrating method GetHashCode of class String. 3 4 Imports System.Windows.Forms 5 6 Module modHashCode 7 8 Sub Main() 9Dim string1 As String = "hello" 10 Dim string2 As String = "Hello" 11 Dim output As String 12 Dim quotes AsString = ChrW(34) 13 14 output = "The hash code for " & quotes & string1 & _ 15quotes & " is " & string1.GetHashCode() & vbCrLf 16 17 output &= "The has code for " & quotes & string2 & _ 18 quotes & " is " & string2.GetHashCode() 19 20 MessageBox.Show(output, _ 21 "Demonstrating String Method GetHashCode") 22 End Sub ' Main 23 24 End Module ' modHashCode StringHashCode.vbCall to GetHashCodeCall to GetHashCode

  17. Alternative toChrW(34).Two consecutive double quotation marks ("") produces one double quotation mark in the String Finds first occurrence of c in Stringletters Finds first occurrence of a in letters, starting at position 1 Searches for occurrence of $ in letters starting at position 3 and searching for 5 characters.Returns –1, indicating there is no occurrence Finds last occurrence of c Finds last occurrence of $ searching back from position 15 for 5 characters.Returns -1 Finds last occurrence of a by searching back from position 25 1 ' Fig. 15.6: StringIndexMethods.vb 2 ' Using String searching methods. 3 4 Imports System.Windows.Forms 5 6 Module modIndexMethods 7 8 SubMain() 9 Dim letters AsString = "abcdefghijklmabcdefghijklm" 10 Dim output AsString 11 Dim searchLetters AsChar() = NewChar() {"c"c, "a"c, "$"c} 12 13 ' test IndexOf to locate a character in a string 14 output &= """c"" is located at index " & _ 15 letters.IndexOf("c"c) 16 17 output &= vbCrLf & """a"" is located at index " & _ 18 letters.IndexOf("a"c, 1) 19 20 output &= vbCrLf & """$"" is located at index " & _ 21 letters.IndexOf("$"c, 3, 5) 22 23 ' test LastIndexOf to find a character in a string 24 output &= vbCrLf & vbCrLf & "Last ""c"" is located at " & _ 25"index " & letters.LastIndexOf("c"c) 26 27 output &= vbCrLf & "Last ""a"" is located at index " & _ 28 letters.LastIndexOf("a"c, 25) 29 30 output &= vbCrLf & "Last ""$"" is located at index " & _ 31 letters.LastIndexOf("$"c, 15, 5) 32 StringIndexMethods.vbCalls to IndexOfCalls to LastIndexOf

  18. Whereas previous calls to IndexOf searched for a character, this call finds the substring "def" Searches for "def" starting at position 7 Searches for "hello" starting at position 5, continuing for 15 characters Searches from end of String to find last occurrence of "def" Searches back from position 25 Searches back from position 20 for 15 characters Searches for first occurrence of any character in searchLetters array Searches for first occurrence of a character in searchLetters, starting at position 7 Searches for 5 characters starting at position 20 33 ' test IndexOf to locate a substring in a string 34 output &= vbCrLf & vbCrLf & """def"" is located at" & _ 35 " index " & letters.IndexOf("def") 36 37 output &= vbCrLf & """def"" is located at index " & _ 38 letters.IndexOf("def", 7) 39 40 output &= vbCrLf & """hello"" is located at index " & _ 41 letters.IndexOf("hello", 5, 15) 42 43 ' test LastIndexOf to find a substring in a string 44 output &= vbCrLf & vbCrLf & "Last ""def"" is located " & _ 45"at index " & letters.LastIndexOf("def") 46 47 output &= vbCrLf & "Last ""def"" is located at " & _ 48 letters.LastIndexOf("def", 25) 49 50 output &= vbCrLf & "Last ""hello"" is located at " & _ 51"index " & letters.LastIndexOf("hello", 20, 15) 52 53 ' test IndexOfAny to find first occurrence of character 54 ' in array 55 output &= vbCrLf & vbCrLf & "First occurrence of ""c""," & _ 56 " ""a""or ""$"" is located at " & _ 57 letters.IndexOfAny(searchLetters) 58 59 output &= vbCrLf & "First occurrence of ""c"", ""a"" or " & _ 60 """$"" is located at " & _ 61 letters.IndexOfAny(searchLetters, 7) 62 63 output &= vbCrLf & "First occurrence of ""c"", ""a"" or " & _ 64 """$"" is located at " & _ 65 letters.IndexOfAny(searchLetters, 20, 5) 66 StringIndexMethods.vbCalls to IndexOfCalls to LastIndexOfCalls to IndexOfAny

  19. Searches for last occurrence of any in an array of characters Searches back from position 1 Searches back from position 25 for 5 characters 67 ' test LastIndexOfAny to find first occurrence of character 68 ' in array 69 output &= vbCrLf & vbCrLf & "Last occurrence of ""c""," & _ 70 " ""a"" or ""$"" is located at " & _ 71 letters.LastIndexOfAny(searchLetters) 72 73 output &= vbCrLf & "Last occurrence of ""c"", ""a"" or " & _ 74 """$"" is located at " & _ 75 letters.LastIndexOfAny(searchLetters, 1) 76 77 output &= vbCrLf & "Last occurrence of ""c"", ""a"" or " & _ 78 """$""is located at " & _ 79 letters.LastIndexOfAny(searchLetters, 25, 5) 80 81 MessageBox.Show(output, _ 82 "Demonstrating String class index methods") 83 EndSub' Main 84 85 EndModule' modIndexMethods StringIndexMethods.vbCalls to LastIndexOfAny

  20. StringIndexMethods.vb

  21. Method Substring returns a new String object generated by copying characters from the calling String.One argument version returns characters between position indicated and end of String Two argument version returns substring starting at position indicated by first argument with length indicated by second argument 1 ' Fig. 15.7: SubString.vb 2 ' Demonstrating the String Substring method. 3 4 Imports System.Windows.Forms 5 6 Module modSubString 7 8 Sub Main() 9 Dim letters As String = "abcdefghijklmabcdefghijklm" 10 Dim output As String 11 Dim quotes AsString = ChrW(34) 12 13 ' invoke SubString method and pass it one parameter 14 output = "Substring from index 20 to end is " & _ 15quotes & letters.Substring(20) & quotes & vbCrLf 16 17 ' invoke SubString method and pass it two parameters 18 output &= "Substring from index 0 to 6 is " &_ 19 quotes& letters.Substring(0, 6) & quotes 20 21 MessageBox.Show(output, _ 22 "Demonstrating String method Substring") 23 End Sub ' Main 24 25 End Module ' modSubString SubString.vbCall to SubstringCall to Substring

  22. Shared method Concat returns a new String object containing the combined characters from both original Strings 1 ' Fig. 15.8: SubConcatination.vb 2 ' Demonstrating String class ConCat method. 3 4 Imports System.Windows.Forms 5 6 Module modSubConcat 7 8 Sub Main() 9 Dim string1 As String = "Happy " 10 Dim string2 As String = "Birthday" 11 Dim output As String 12 13 output = "string1 = """ &string1 & """" & _ 14 vbCrLf & "string2 = """ & string2 & """" 15 16 output &= vbCrLf & vbCrLf & _ 17 "Result of String.Concat(string1, string2) = " & _ 18String.Concat(string1, string2) 19 20 MessageBox.Show(output, _ 21 "Demonstrating String method Concat") 22 End Sub ' Main 23 24 End Module ' modSubConcat SubConcatination.vbCall to Concat

  23. Method Replace replaces every instance of the character indicated by the first argument with the second argument Method ToUpper creates a new Stringwith all lowercase characters converted to uppercase Converts all uppercase characters to lowercase 1 ' Fig. 15.9: StringMiscellaneous.vb 2 ' Demonstrating String methods Replace, ToLower, ToUpper, Trim, 3 ' and ToString. 4 5 Imports System.Windows.Forms 6 7 Module modStringMiscellaneous 8 9 Sub Main() 10 Dim string1 As String = "cheers!" 11 Dim string2 As String = "GOOD BYE " 12 Dim string3 As String = " spaces " 13 Dim output As String 14 Dim quotes AsString = ChrW(34) 15 Dim i As Integer 16 17 output = "string1 = " & quotes & string1 & quotes & _ 18 vbCrLf & "string2 = " & quotes & string2 & quotes & _ 19 vbCrLf & "string3 = " & quotes & string3 & quotes 20 21 ' call method Replace 22 output &= vbCrLf & vbCrLf & "Replacing " & quotes & "e" & _ 23 quotes & " with " & quotes & "E" & quotes & _ 24" in string1: " & quotes & string1.Replace("e"c, "E"c) & _ 25 quotes 26 27 ' call ToLower and ToUpper 28 output &= vbCrLf & vbCrLf & "string1.ToUpper() = " & _ 29 quotes & string1.ToUpper() & quotes & vbCrLf & _ 30"string2.ToLower() = " & quotes & string2.ToLower() & _ 31 quotes 32 StringMiscellaneous.vbCall to ReplaceCall to ToUpper Call to ToLower

  24. Method Trim returns a copy of the calling String with leading and trailing whitespace characters removed Method ToString is provided for class String because String is derived from class Object 33 ' call Trim method 34 output &= vbCrLf & vbCrLf & "string3 after trim = " & _ 35 quotes & string3.Trim() & quotes 36 37 ' call ToString method 38 output &= vbCrLf & vbCrLf & "string1 = " & _ 39 quotes & string1.ToString() & quotes 40 41 MessageBox.Show(output, _ 42 "Demonstrating Miscellaneous String Methods") 43 End Sub ' Main 44 45 End Module ' modStringMiscellaneous StringMiscellaneous.vbCall to TrimCall to ToString

  25. 15.11  ClassStringBuilder • Disadvantages of class String • Contents of a Stringobject can not be modified after creation • Concatenation and most String operations require creation of a new String object • Class StringBuilder • System.Text namespace • Stores a modifiable string of characters • Has a set capacity that can be increased when necessary • More efficient than String if string is modified repeatedly • Less efficient than String if string is fixed • Upcoming example: StringBuilder class constructors

  26. Creates a StringBuilder with no characters and default initial capacity of 16 characters Creates empty StringBuilder with capacity 10 Creates StringBuilder containing contents of String argument.Initial capacity is smallest power of two greater than the number of characters in argument String Must call method ToString to use concatenation operator 1 ' Fig. 15.10: StringBuilderConstructor.vb 2 ' Demonstrating StringBuilder class constructors. 3 4 Imports System.Text 5 Imports System.Windows.Forms 6 7 Module modBuilderConstructor 8 9 Sub Main() 10 Dim buffer1, buffer2, buffer3 As StringBuilder 11 Dim quotes AsString = ChrW(34) 12 Dim output As String 13 14 buffer1 = New StringBuilder() 15 buffer2 = New StringBuilder(10) 16 buffer3 = New StringBuilder("hello") 17 18 output = "buffer1 = " & quotes & buffer1.ToString() & _ 19 quotes & vbCrLf 20 21 output &= "buffer2 = " & quotes & _ 22 buffer2.ToString() & quotes & vbCrLf 23 24 output &= "buffer3 = " & quotes & _ 25 buffer3.ToString() & quotes 26 27 MessageBox.Show(output, _ 28 "Demonstrating StringBuilder Class Constructors") 29 End Sub ' Main 30 31 End Module ' modBuilderConstructor StringBuilderConstructor.vbCalls to constructors

  27. StringBuilderConstructor.vb

  28. 15.12  StringBuilder Indexer, Length and CapacityProperties, and EnsureCapacity Method • StringBuilder capacities • Number of characters that can be stored without allocating more memory • Returned by Capacity property • Length property returns number of characters stored • Method EnsureCapacity • Guarantees capacity greater than specified value • New capacity determined by: • Doubling current capacity if large enough, or • Making new capacity one larger than capacity requested • Upcoming example: StringBuilder size manipulation

  29. Creates new StringBuilder with contents of String argument Returns number of characters stored (19) Returns capacity of StringBuilder (32) Ensures that capacity is at least 75 New capacity is 76 (one larger than 75) Displays length of internal string (10) Reduces contents to the first ten characters.Does not alter capacity Indexer used to return character at position i 1 ' Fig. 15.11: StringBuilderFeatures.vb 2 ' Demonstrating some features of class StringBuilder. 3 4 Imports System.Text 5 Imports System.Windows.Forms 6 7 Module modBuilderFeatures 8 9 Sub Main() 10 Dim i As Integer 11 Dim buffer As StringBuilder = _ 12New StringBuilder("Hello, how are you?") 13 14 ' use Length and Capacity properties 15 Dim output As String = "buffer = " & buffer.ToString & _ 16vbCrLf & "Length = " & buffer.Length & vbCrLf & _ 17"Capacity = " & buffer.Capacity 18 19 ' use EnsureCapacity method 20 buffer.EnsureCapacity(75) 21 22 output &= vbCrLf & vbCrLf & "New capacity = " & _ 23 buffer.Capacity 24 25 ' truncate StringBuilder by setting Length property 26 buffer.Length = 10 27 28 output &= vbCrLf & vbCrLf & "New Length = " & _ 29 buffer.Length & vbCrLf & "buffer = " 30 31 ' use StringBuilder Indexer 32 For i = 0To buffer.Length - 1 33 output &= buffer(i) 34 Next 35 StringBuilderFeatures.vbLength propertyCapacity propertyCall to EnsureCapacityIndexer

  30. 36 MessageBox.Show(output, "StringBuilder Features") 37 End Sub ' Main 38 39 End Module ' modBuilderFeatures StringBuilderFeatures.vb

  31. 19 different overloaded Append methods allow various data types (in this case an Object) to be concatenated onto StringBuilder contents Create empty StringBuilder Appends a String literal Appends a String object Appends each value in an array of characters Appends 3 characters from the array, starting at index 0 Appends string representation of Boolean value Appends a single character 1 ' Fig. 15.12: StringBuilderAppend.vb 2 ' Demonstrating StringBuilder Append methods. 3 4 Imports System.Text 5 Imports System.Windows.Forms 6 7 Module modBuilderAppend 8 9 Sub Main() 10 Dim objectValue As Object = "hello" 11 Dim stringValue As String = "good bye" 12 Dim characterArray() As Char = {"a"c, "b"c, "c"c, _ 13 "d"c, "e"c, "f"c} 14 15 Dim booleanValue As Boolean = True 16 Dim characterValue As Char = "Z"c 17 Dim integerValue As Integer = 7 18 Dim longValue As Long = 1000000 19 Dim singleValue As Single = 2.5F 20 Dim doubleValue As Double = 33.333 21Dim buffer As StringBuilder = New StringBuilder() 22 23 ' use method Append to append values to buffer 24 buffer.Append(objectValue) 25 buffer.Append(" ") 26 buffer.Append(stringValue) 27 buffer.Append(" ") 28 buffer.Append(characterArray) 29 buffer.Append(" ") 30 buffer.Append(characterArray, 0, 3) 31 buffer.Append(" ") 32 buffer.Append(booleanValue) 33 buffer.Append(" ") 34 buffer.Append(characterValue) 35 buffer.Append(" ") StringBuilderAppend.vbCalls to Append

  32. Appends an integer Appends a Long integer Appends a Single Appends a Double 36buffer.Append(integerValue) 37 buffer.Append(" ") 38 buffer.Append(longValue) 39 buffer.Append(" ") 40 buffer.Append(singleValue) 41 buffer.Append(" ") 42 buffer.Append(doubleValue) 43 44 MessageBox.Show("buffer = " & buffer.ToString(), _ 45 "Demonstrating StringBuilder Append Methods",_ 46 MessageBoxButtons.OK, MessageBoxIcon.Information) 47 End Sub ' Main 48 49 End Module ' modBuilderAppend StringBuilderAppend.vb

  33. Format allows a value to be placed in a String at a particular location Indicates value should be formatted as a currency Creates a String with formatting information Substitutes values contained in objectArray for formats in string1 and appends result to buffer contents Formats value as a three-digit decimal integer Value displayed in four spaces, aligned to the right Negative number aligns value to the left Value of second argument is substituted for formats in string2, then contents are appended to buffer 1 ' Fig. 15.13: StringBuilderAppendFormat.vb 2 ' Demonstrating method AppendFormat. 3 4 Imports System.Text 5 Imports System.Windows.Forms 6 7 Module modBuilderAppendFormat 8 9 Sub Main() 10 Dim buffer As StringBuilder = New StringBuilder() 11 Dim string1, string2 AsString 12 13 ' formatted string 14 string1 = "This {0} costs :{1:C}." & vbCrLf 15 16 ' string1 argument array 17 Dim objectArray AsObject()= New Object(1) {} 18 19 objectArray(0) = "car" 20 objectArray(1) = 1234.56 21 22 ' append to buffer formatted string with argument 23 buffer.AppendFormat(string1, objectArray) 24 25 ' formatted string 26 string2 = "Number:{0:D3}. " & vbCrLf & _ 27 "Number right aligned with spaces:{0, 4}." & vbCrLf & _ 28"Number left aligned with spaces:{0, -4}." 29 30 ' append to buffer formatted string with argument 31 buffer.AppendFormat(string2, 5) 32 StringBuilderAppendFormat.vbCall to AppendFormat

  34. 33 ' display formatted strings 34 MessageBox.Show(buffer.ToString(), "Using AppendFormat", _ 35 MessageBoxButtons.OK, MessageBoxIcon.Information) 36 EndSub' Main 37 38 EndModule' modBuilderAppendFormat StringBuilderAppendFormat.vb

  35. 18 overloaded Insert methods allow values of various data types to be inserted at a specific location 1 ' Fig. 15.14: StringBuilderInsertRemove.vb 2 ' Demonstrating methods Insert and Remove of the 3 ' StringBuilder class. 4 5 Imports System.Text 6 Imports System.Windows.Forms 7 8 Module modBuilderInsertRemove 9 10 Sub Main() 11 Dim objectValue As Object = "hello" 12 Dim stringValue As String = "good bye" 13 Dim characterArray() As Char = {"a"c, "b"c, "c"c, _ 14 "d"c, "e"c, "f"c} 15 16 Dim booleanValue As Boolean = True 17 Dim characterValue As Char = "K"c 18 Dim integerValue As Integer = 7 19 Dim longValue As Long = 10000000 20 Dim singleValue As Single = 2.5 21 Dim doubleValue As Double = 33.333 22 Dim buffer As StringBuilder = New StringBuilder() 23 Dim output As String 24 25 ' insert values into buffer 26 buffer.Insert(0, objectValue) 27 buffer.Insert(0, " ") 28 buffer.Insert(0, stringValue) 29 buffer.Insert(0, " ") 30 buffer.Insert(0, characterArray) 31 buffer.Insert(0, " ") 32 buffer.Insert(0, booleanValue) 33 buffer.Insert(0, " ") 34 buffer.Insert(0, characterValue) 35 buffer.Insert(0, " ") StringBuilderInsertRemove.vbCalls to Insert

  36. Method Remove deletes the number of characters specified by the second argument, starting at the location specified by the first argument 36 buffer.Insert(0, integerValue) 37 buffer.Insert(0, " ") 38 buffer.Insert(0, longValue) 39 buffer.Insert(0, " ") 40 buffer.Insert(0, singleValue) 41 buffer.Insert(0, " ") 42 buffer.Insert(0, doubleValue) 43 buffer.Insert(0, " ") 44 45 output = "buffer after inserts:" & vbCrLf & _ 46 buffer.ToString() & vbCrLf & vbCrLf 47 48 buffer.Remove(12, 1) ' delete 5 in 2.5 49 buffer.Remove(2, 4) ' delete .333 in 33.333 50 51 output &= "buffer after Removes:" & vbCrLf & _ 52 buffer.ToString() 53 54 MessageBox.Show(output, "Demonstrating StringBuilder " & _ 55 "Insert and Remove Methods", MessageBoxButtons.OK, _ 56 MessageBoxIcon.Information) 57 End Sub ' Main 58 59 End Module ' modBuilderInsertRemove StringBuilderInsertRemove.vbCalls to Remove

  37. Method Replace locates all instances of the first argument and replaces them with the contents of the second argument In this case, first character is replaced by second character if it falls in the 5 positions starting at index 0 1 ' Fig. 15.15: StringBuilderReplace.vb 2 ' Demonstrating method Replace. 3 4 Imports System.Text 5 Imports System.Windows.Forms 6 7 Module modBuilderReplace 8 9 Sub Main() 10 Dim builder1 As StringBuilder = _ 11 New StringBuilder("Happy Birthday Jane") 12 13 Dim builder2 As StringBuilder= _ 14 New StringBuilder("good bye greg") 15 16 Dim output As String = "Before Replacements:" & vbCrLf & _ 17 builder1.ToString() & vbCrLf & builder2.ToString() 18 19 builder1.Replace("Jane", "Greg") 20 builder2.Replace("g"c, "G"c, 0, 5) 21 22 output &= vbCrLf & vbCrLf & "After Replacements:" & _ 23 vbCrLf & builder1.ToString() & vbCrLf & _ 24 builder2.ToString() 25 26 MessageBox.Show(output,_ 27 "Using StringBuilder method Replace", _ 28 MessageBoxButtons.OK, MessageBoxIcon.Information) 29 End Sub ' Main 30 31 End Module ' modBuilderReplace StringBuilderReplace.vbCalls to Replace

  38. StringBuilderReplace.vb

  39. 15.15 Char Methods • Structures • Program building blocks similar to classes • Encapsulate value types • Have methods and properties • Passed by value unless keyword ByRef used • Many data type keywords (e.g., Integer) are aliases for structures (e.g., System.Int32) • Created using keyword Structure • Char is example of structure • Upcoming example: Char’s Shared character-testing methods and case-conversion methods

  40. Reads user input Generates program output Method IsDigit returns a Boolean indicating if argument is a digit 1 ' Fig. 15.16: CharMethods.vb 2 ' Demonstrates Shared character testing methods 3 ' from Char structure 4 5 Public Class FrmCharacter 6 Inherits Form 7 8 Friend WithEventslblEnter AsLabel' prompts for input 9 10 Friend WithEventstxtInput AsTextBox' reads a Char 11 Friend WithEventstxtOutput AsTextBox' displays results 12 13 ' reads and displays information about input 14 Friend WithEventscmdAnalyze AsButton 15 16 ' Visual Studio .NET generated code 17 18 ' handle cmdAnalyze Click 19Private Sub cmdAnalyze_Click(ByVal sender As System.Object, _ 20 ByVal e As System.EventArgs) Handles cmdAnalyze.Click 21 22 Dim character AsChar = Convert.ToChar(txtInput.Text) 23 24 BuildOutput(character) 25 EndSub' cmdAnalyze_Click 26 27 ' display character information in txtOutput 28 Public Sub BuildOutput(ByVal inputCharacter) 29 Dim output As String 30 31 output = "is digit: " & _ 32 Char.IsDigit(inputCharacter) & vbCrLf 33 CharMethods.vbDefine FrmCharactercmdAnalyze_ClickCall to BuildOutputBuildOutputCall to IsDigit

  41. Determines if argument is a letter Determines if argument is lowercase Determines if argument is uppercase Converts argument to uppercase Converts argument to lowercase Determines if argument is a punctuation character Determines if argument is a symbol Determines if argument is a letter or a digit 34 output &= "is letter: " & _ 35 Char.IsLetter(inputCharacter) & vbCrLf 36 37 output &= "is letter or digit: " & _ 38 Char.IsLetterOrDigit(inputCharacter) & vbCrLf 39 40 output &= "is lower case: " & _ 41Char.IsLower(inputCharacter) & vbCrLf 42 43 output &= "is upper case or digit: " & _ 44 Char.IsUpper(inputCharacter) & vbCrLf 45 46 output &= "to upper case: " & _ 47 Char.ToUpper(inputCharacter) & vbCrLf 48 49 output &= "to lower case: " & _ 50 Char.ToLower(inputCharacter) & vbCrLf 51 52 output &= "is punctuation: " & _ 53 Char.IsPunctuation(inputCharacter) & vbCrLf 54 55 output &= "is symbol: " & Char.IsSymbol(inputCharacter) 56 57 txtOutput.Text =output 58 End Sub ' BuildOutput 59 60 End Class' FrmCharacter CharMethods.vbCall to IsLetterCall to IsLetterOrDigitCall to IsLowerCall to IsUpperCall to ToUpperCall to ToLowerCall to IsPunctuationCall to IsSymbol

  42. CharMethods.vb

  43. Creates a CCard object with specified face and suit value Method ToString overridden to provide a convenient and consistent String representation of the CCard object 1 ' Fig. 15.17: Card.vb 2 ' Stores suit and face information on each card. 3 4 Class CCard 5 Private face AsString 6 Private suit AsString 7 8PublicSub New(ByVal faceValue AsString, _ 9 ByVal suitValue AsString) 10 11 face = faceValue 12 suit = suitValue 13 EndSub' New 14 15PublicOverridesFunction ToString() AsString 16 Return face & " of " & suit 17 EndFunction' ToString 18 19 EndClass' CCard Card.vbDefine CCardConstructorToString

  44. Initializes the deck array when form loads An array of CCard objects Ordered array of face names Array of suit names 1 ' Fig. 15.18: DeckOfCards.vb 2 ' Simulating card drawing and shuffling. 3 4 PublicClass FrmDeck 5 Inherits Form 6 7 Friend WithEventslblDisplay AsLabel' displays dealt card 8 Friend WithEventslblStatus AsLabel' number of cards dealt 9 10 Friend WithEventscmdDeal AsButton' deal one card 11 Friend WithEventscmdShuffle AsButton' shuffle cards 12 13 ' Visual Studio.NET generated code 14 15 Private currentCardAs Integer 16 Private randomObject AsRandom = New Random() 17Private deckAs CCard() =New CCard(51) {} 18 19 ' handles form at load time 20PublicSub FrmDeck_Load(ByVal sender As System.Object, _ 21 ByVal e As System.EventArgs) HandlesMyBase.Load 22 23Dim faces As String() = {"Ace", "Deuce", "Three", _ 24 "Four", "Five", "Six", "Seven", "Eight", "Nine", _ 25 "Ten", "Jack", "Queen", "King"} 26 27 Dim suits As String() = {"Hearts", "Diamonds", "Clubs",_ 28 "Spades"} 29 30 Dim i As Integer 31 32 ' no cards have been drawn 33 currentCard = -1 34 DeckOfCards.vbDefine FrmDeckFrmDeck_Load

  45. Create 52 unique CCard objects Deals a single card or returns Nothing if deck is empty Deals the next CCard object from the deck Calling overridden method ToString produces a String representation of the CCard object Reorders deck randomly 35 ' initialize deck 36 For i = 0To deck.GetUpperBound(0) 37 deck(i) = New CCard(faces(i Mod13), suits(i Mod4)) 38 Next 39 40 End Sub ' DeckCards 41 42 ' handles cmdDeal Click 43 Private Sub cmdDeal_Click(ByVal sender As System.Object, _ 44 ByVal e As System.EventArgs) Handles cmdDeal.Click 45 46Dim dealt As CCard = DealCard() 47 48 ' if dealt card is Nothing, then no cards left 49 ' player must shuffle cards 50 IfNot (dealt IsNothing) Then 51 lblDisplay.Text = dealt.ToString() 52 lblStatus.Text = "Card #: " & currentCard 53 Else 54 lblDisplay.Text = "NO MORE CARDS TO DEAL" 55 lblStatus.Text = "Shuffle cards to continue" 56 End If 57 58 End Sub ' cmdDeal_Click 59 60 ' shuffle cards 61PublicSub Shuffle() 62 Dim i AsInteger 63 Dim j As Integer 64 Dim temporaryValue As CCard 65 66 currentCard = -1 67 DeckOfCards.vbcmdDeal_ClickCall to DealCardCall to ToStringShuffle

  46. Each CCard in deck is swapped into another random position Returns the next CCard from the deck If no cards are left, disable cmdDeal and return Nothing 68 ' swap each card with random card 69For i = 0To deck.GetUpperBound(0) 70 j = randomObject.Next(52) 71 72 ' swap cards 73 temporaryValue= deck(i) 74 deck(i) = deck(j) 75 deck(j) = temporaryValue 76 Next 77 78 cmdDeal.Enabled = True 79 End Sub ' Shuffle 80 81PublicFunction DealCard() As CCard 82 83 ' if there is a card to deal then deal it 84 ' otherwise signal that cards need to be shuffled by 85 ' disabling cmdDeal and returning Nothing 86 If (currentCard + 1) < deck.GetUpperBound(0) Then 87 currentCard += 1 88 89 Return deck(currentCard) 90Else 91 cmdDeal.Enabled = False 92 93 ReturnNothing 94 End If 95 96 End Function ' DealCard 97 DeckOfCards.vbDealCard

  47. Calls Shuffle to place cards in random order 98 ' cmdShuffle_Click 99 Private Sub cmdShuffle_Click(ByVal sender As System.Object, _ 100 ByVal e As System.EventArgs) Handles cmdShuffle.Click 101 102 lblDisplay.Text = "SHUFFLING..." 103 104 Shuffle() 105 106 lblDisplay.Text = "DECK IS SHUFFLED" 107 End Sub ' cmdShuffle_Click 108 109 End Class ' FrmDeck DeckOfCards.vbcmdShuffle_ClickCall to Shuffle

  48. DeckOfCards.vb

  49. 15.17  Regular Expressions and Class Regex • Regular expressions • Specially formatted Strings used to find patterns in text • Find special formats (e.g., ZIP codes, telephone numbers) • Class Regex (System.Text.RegularExpressions) • Method Match returns object of class Match • Method Matches returns MatchCollection object

  50. 15.17  Regular Expressions and Class Regex • Regular expression syntax • Character literals • Match a specific character • Usually indicated by the character itself • Dot character, . • Matches any single character except newline • Character classes • Match any of a designated set of characters • Preceded by a backslash, \ (used as escape character) • Distinguishes character class from character literal

More Related