22
2002 Prentice Hall. All rights reserved. 1 Chapter 15 – Strings, Characters and Regular Expressions Outline 15.1 Introduction 15.2 Fundamentals of Characters and Strings 15.3 String Constructors 15.4 String Length and Chars Properties and CopyTo Method 15.5 Comparing Strings 15.6 String Method GetHashCode 15.7 Locating Characters and Substrings in Strings 15.8 Extracting Substrings from Strings 15.9 Concatenating Strings 15.10 Miscellaneous String Methods 15.11 Class StringBuilder 15.12 StringBuilder Indexer, Length and Capacity Properties, and EnsureCapacity Method 15.13 StringBuilder Append and AppendFormat Methods 15.14 StringBuilder Insert, Remove and Replace Methods 15.15 Char Methods 15.16 Card Shuffling and Dealing Simulation

Chapter 15 – Strings, Characters and Regular Expressions

  • Upload
    lamya

  • View
    32

  • Download
    1

Embed Size (px)

DESCRIPTION

Chapter 15 – Strings, Characters and Regular Expressions. - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall. All rights reserved.

1

Chapter 15 – Strings, Characters and Regular Expressions

Outline15.1 Introduction15.2   Fundamentals of Characters and Strings15.3   String Constructors15.4   String Length 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  Class StringBuilder15.12  StringBuilder Indexer, Length and Capacity Properties, and EnsureCapacity Method15.13   StringBuilder Append and AppendFormat Methods15.14   StringBuilder Insert, Remove and Replace Methods15.15 Char Methods15.16   Card Shuffling and Dealing Simulation15.17   Regular Expressions and Class Regex

Page 2: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall. All rights reserved.

2

15.1Introduction

• 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

Page 3: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall. All rights reserved.

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

Page 4: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall. All rights reserved.

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

Page 5: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline5

StringConstructor.vb

ChrW function

Calls to String constructors

1 ' Fig. 15.1: StringConstructor.vb2 ' Demonstrating String class constructors.3 4 Imports System.Windows.Forms5 6 Module modStringConstructor7 8 Sub Main()9 Dim characterArray As Char()10 Dim output As String11 Dim quotes As String = ChrW(34)12 Dim originalString, string1, string2, string3, _13 string4 As String14 15 characterArray = New Char() {"b"c, "i"c, "r"c, _16 "t"c, "h"c, " "c, "d"c, "a"c, "y"c}17 18 ' string initialization19 originalString = "Welcome to VB.NET Programming!"20 string1 = originalString21 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 & quotes29 30 MessageBox.Show(output, "String Class Constructors", _31 MessageBoxButtons.OK, MessageBoxIcon.Information)32 End Sub ' Main33 34 End Module ' modStringConstructor

ChrW converts Unicode value 34 to double quote character, "

Creates an array of type Char.Suffix c required when using Option Strict

Creates a literal String object

string1 and originalString reference same literal String object

Creates a new String object containing a copy of characters in characterArray

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, "

Page 6: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline6

StringConstructor.vb

Page 7: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline7

StringMiscellaneous.vb

1 ' Fig. 15.2: StringMiscellaneous.vb2 ' Using properties Length and Chars3 ' of class string.4 5 Imports System.Windows.Forms6 7 Module modMiscellaneous8 9 Sub Main()10 Dim string1, output As String11 Dim characterArray As Char()12 Dim i As Integer13 Dim quotes As String = ChrW(34)14 15 string1 = "hello there"16 characterArray = New Char(5) {}17 18 ' output string19 output = "string1: " & quotes & string1 & quotes20 21 ' test Length property22 output &= vbCrLf & "Length of string1: " & string1.Length23 24 ' loop through characters in string1 and display 25 ' reversed26 output &= vbCrLf & "The string reversed is: "27 28 For i = string1.Length - 1 To 0 Step -129 output &= string1.Chars(i)30 Next31 32 ' copy characters from string1 into characterArray33 string1.CopyTo(0, characterArray, 0, 5)34 output &= vbCrLf & "The character array is: "35

Length property returns number of characters in string

Length property used to loop backwards through characters in string1

Returns the character at the position indicated by the integer argument

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

Page 8: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline8

StringMiscellaneous.vb

36 For i = 0 To characterArray.Length - 137 output &= characterArray(i)38 Next39 40 MessageBox.Show(output, "Demonstrating String" & _41 " properties Length and Chars", _42 MessageBoxButtons.OK, MessageBoxIcon.Information)43 End Sub ' Main44 45 End Module ' modMiscellaneous

Displays contents of characterArray

Page 9: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall. All rights reserved.

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– Is operator

– Upcoming example: String test to determine equality

Page 10: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline10

StringCompare.vb

Call to Equals

= operator

1 ' Fig. 15.3: StringCompare.vb2 ' Comparing strings.3 4 Imports System.Windows.Forms5 6 Module modCompare7 8 Sub Main()9 Dim string1 As String = "hello"10 Dim string2 As String = "good bye"11 Dim string3 As String = "Happy Birthday"12 Dim string4 As String = "happy birthday"13 Dim output As String14 Dim quotes As String = ChrW(34)15 16 ' output values of four Strings17 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 & vbCrLf22 23 ' test for equality using Equals method24 If (string1.Equals("hello")) Then25 output &= "string1 equals " & quotes & "hello" & _26 quotes & vbCrLf2728 Else29 output &= "string1 does not equal " & quotes & _30 "hello" & quotes & vbCrLf31 End If32 33 ' test for equality with =34 If string1 = "hello" Then35 output &= "string1 equals " & quotes & "hello" & _

Method Equals performs case-sensitive lexicographical comparison

Equality operator produces same results as method Equals

Page 11: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline11

StringCompare.vb

Call to Equals

Call to CompareTo

36 quotes & vbCrLf37 Else38 output &= "string1 does not equal " & quotes & _39 "hello" & quotes & vbCrLf40 End If41 42 ' test for equality comparing case43 If (String.Equals(string3, string4)) Then44 output &= "string3 equals string4" & vbCrLf45 Else46 output &= "string3 does not equal string4" & vbCrLf47 End If48 49 ' test CompareTo50 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 & vbCrLf60 61 MessageBox.Show(output, "Demonstrating string" & _62 " comparisons", MessageBoxButtons.OK, _63 MessageBoxIcon.Information)64 End Sub ' Main65 66 End Module ' modCompare

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

Page 12: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline12

StringCompare.vb

Page 13: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline13

StringStartEnd.vb

Call to StartsWith

Call to EndsWith

1 ' Fig. 15.4: StringStartEnd.vb2 ' Demonstrating StartsWith and EndsWith methods.3 4 Imports System.Windows.Forms5 6 Module modStartEnd7 8 Sub Main()9 Dim strings As String()10 Dim output As String = ""11 Dim i As Integer12 Dim quotes As String = ChrW(34)13 14 strings = New String() {"started", "starting", _15 "ended", "ending"}16 17 ' test every string to see if it starts with "st"18 For i = 0 To strings.GetUpperBound(0)19 20 If strings(i).StartsWith("st") Then21 output &= quotes & strings(i) & quotes & _22 " starts with " & quotes & "st" & quotes & vbCrLf23 End If24 25 Next26 27 output &= vbCrLf28 29 ' test every string to see if it ends with "ed"30 For i = 0 To strings.GetUpperBound(0)31 32 If strings(i).EndsWith("ed") Then33 output &= quotes & strings(i) & quotes & _34 " ends with " & quotes & "ed" & quotes & vbCrLf

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

Page 14: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline14

StringStartEnd.vb

35 End If36 37 Next38 39 MessageBox.Show(output, "Demonstrating StartsWith and" & _40 " EndsWith methods", MessageBoxButtons.OK, _41 MessageBoxIcon.Information)42 End Sub ' Main43 44 End Module ' modStartEnd

Page 15: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline15

StringIndexMethods.vb

Calls to IndexOf

Calls to LastIndexOf

1 ' Fig. 15.6: StringIndexMethods.vb2 ' Using String searching methods.3 4 Imports System.Windows.Forms5 6 Module modIndexMethods7 8 Sub Main()9 Dim letters As String = "abcdefghijklmabcdefghijklm"10 Dim output As String 11 Dim searchLetters As Char() = New Char() {"c"c, "a"c, "$"c}12 13 ' test IndexOf to locate a character in a string14 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 string24 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

Alternative to ChrW(34).Two consecutive double quotation marks ("") produces one double quotation mark in the String

Finds first occurrence of c in String letters

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 a by searching back from position 25

Finds last occurrence of $ searching back from position 15 for 5 characters.Returns -1

Page 16: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline16

StringIndexMethods.vb

Calls to IndexOf

Calls to LastIndexOf

Calls to IndexOfAny

33 ' test IndexOf to locate a substring in a string34 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 string44 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 array55 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

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

Page 17: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline17

StringIndexMethods.vb

Calls to LastIndexOfAny

67 ' test LastIndexOfAny to find first occurrence of character 68 ' in array69 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 End Sub ' Main84 85 End Module ' modIndexMethods

Searches for last occurrence of any in an array of characters

Searches back from position 1

Searches back from position 25 for 5 characters

Page 18: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline18

StringIndexMethods.vb

Page 19: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline19

SubString.vb

Call to Substring

Call to Substring

1 ' Fig. 15.7: SubString.vb2 ' Demonstrating the String Substring method.3 4 Imports System.Windows.Forms5 6 Module modSubString7 8 Sub Main()9 Dim letters As String = "abcdefghijklmabcdefghijklm"10 Dim output As String 11 Dim quotes As String = ChrW(34)12 13 ' invoke SubString method and pass it one parameter14 output = "Substring from index 20 to end is " & _15 quotes & letters.Substring(20) & quotes & vbCrLf16 17 ' invoke SubString method and pass it two parameters18 output &= "Substring from index 0 to 6 is " & _19 quotes & letters.Substring(0, 6) & quotes20 21 MessageBox.Show(output, _22 "Demonstrating String method Substring")23 End Sub ' Main24 25 End Module ' modSubString

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

Page 20: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline20

SubConcatination.vb

Call to Concat

1 ' Fig. 15.8: SubConcatination.vb2 ' Demonstrating String class ConCat method.3 4 Imports System.Windows.Forms5 6 Module modSubConcat7 8 Sub Main()9 Dim string1 As String = "Happy "10 Dim string2 As String = "Birthday"11 Dim output As String12 13 output = "string1 = """ & string1 & """" & _14 vbCrLf & "string2 = """ & string2 & """"15 16 output &= vbCrLf & vbCrLf & _17 "Result of String.Concat(string1, string2) = " & _18 String.Concat(string1, string2)19 20 MessageBox.Show(output, _21 "Demonstrating String method Concat")22 End Sub ' Main23 24 End Module ' modSubConcat

Shared method Concat returns a new String object containing the combined characters from both original Strings

Page 21: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline21

StringMiscellaneous.vb

Call to Replace

Call to ToUpper Call to ToLower

1 ' Fig. 15.9: StringMiscellaneous.vb2 ' Demonstrating String methods Replace, ToLower, ToUpper, Trim, 3 ' and ToString.4 5 Imports System.Windows.Forms6 7 Module modStringMiscellaneous8 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 String14 Dim quotes As String = ChrW(34)15 Dim i As Integer16 17 output = "string1 = " & quotes & string1 & quotes & _18 vbCrLf & "string2 = " & quotes & string2 & quotes & _19 vbCrLf & "string3 = " & quotes & string3 & quotes20 21 ' call method Replace22 output &= vbCrLf & vbCrLf & "Replacing " & quotes & "e" & _23 quotes & " with " & quotes & "E" & quotes & _24 " in string1: " & quotes & string1.Replace("e"c, "E"c) & _25 quotes26 27 ' call ToLower and ToUpper28 output &= vbCrLf & vbCrLf & "string1.ToUpper() = " & _29 quotes & string1.ToUpper() & quotes & vbCrLf & _30 "string2.ToLower() = " & quotes & string2.ToLower() & _31 quotes32

Method Replace replaces every instance of the character indicated by the first argument with the second argument

Method ToUpper creates a new String with all lowercase characters converted to uppercase

Converts all uppercase characters to lowercase

Page 22: Chapter 15 – Strings, Characters and Regular Expressions

2002 Prentice Hall.All rights reserved.

Outline22

StringMiscellaneous.vb

Call to Trim

Call to ToString

33 ' call Trim method34 output &= vbCrLf & vbCrLf & "string3 after trim = " & _35 quotes & string3.Trim() & quotes36 37 ' call ToString method38 output &= vbCrLf & vbCrLf & "string1 = " & _39 quotes & string1.ToString() & quotes40 41 MessageBox.Show(output, _42 "Demonstrating Miscellaneous String Methods")43 End Sub ' Main44 45 End Module ' modStringMiscellaneous

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