2006 pearson education, inc. all rights reserved. 1 16 strings, characters and regular expressions
Post on 21-Dec-2015
216 views
TRANSCRIPT
1
2006 Pearson Education, Inc. All rights reserved.
1616Strings, Characters
and Regular Expressions
2
2006 Pearson Education, Inc. All rights reserved.
The chief defect of Henry KingWas chewing little bits of string.
— Hilaire Belloc
Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences.
— William Strunk, Jr.
I have made this letter longer than usual, because I lack the time to make it short.
— Blaise Pascal
3
2006 Pearson Education, Inc. All rights reserved.
The difference between the almost-right word & the right word is really a large matter—it’s the difference between the lightning bug and the lightning.
— Mark Twain
Mum’s the word. — Miguel de Cervantes, Don Quixote de la Mancha
4
2006 Pearson Education, Inc. All rights reserved.
OBJECTIVES
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 struct Char.
To use regular expressions in conjunction with classes Regex and Match.
5
2006 Pearson Education, Inc. All rights reserved.
16.1 Introduction
16.2 Fundamentals of Characters and Strings
16.3 string Constructors
16.4 string Indexer, Length Property and CopyTo Method
16.5 Comparing strings
16.6 Locating Characters and Substrings in strings
16.7 Extracting Substrings from strings
16.8 Concatenating strings
16.9 Miscellaneous string Methods
16.10 Class StringBuilder
16.11 Length and Capacity Properties, EnsureCapacity Method and Indexer of Class StringBuilder
16.12 Append and AppendFormat Methods of Class StringBuilder
6
2006 Pearson Education, Inc. All rights reserved.
16.13 Insert, Remove and Replace Methods of Class StringBuilder
16.14 Char Methods
16.15 Card Shuffling and Dealing Simulation
16.16 Regular Expressions and Class Regex
16.16.1 Regular Expression Example
16.16.2 Validating User Input with Regular Expressions
16.16.3 Regex methods Replace and Split
16.17 Wrap-Up
7
2006 Pearson Education, Inc. All rights reserved.
16.1 Introduction
• FCL’s string and character processing capabilities
– string’s constructors and methods
– StringBuilder from System.Text namespace• Builds strings dynamically
– Regex and Match from the System.Text.RegularExpressions namespace
• Manipulate by patterns
8
2006 Pearson Education, Inc. All rights reserved.
16.2 Fundamentals of Characters and Strings• Characters
– “Building blocks” of C# source programs– Character constant
• A character that is represented as an integer value– Unicode character set
• International character set
• String– Immutable– Series of characters treated as single unit– May include letters, digits, special characters– String literals
• Sequence of characters– From System namespace– To interpret all characters literally use @ before the beginning
quotation mark
9
2006 Pearson Education, Inc. All rights reserved.
Performance Tip 16.1
If there are multiple occurrences of the same string literal object in an application, a single copy of the string literal object will be referenced from each location in the program that uses that string literal. It is possible to share the object in this manner, because string literal objects are implicitly constant. Such sharing conserves memory.
10
2006 Pearson Education, Inc. All rights reserved.
16.3 string Constructors
•string Constructors– Can initialize string as if it was a primitive type
Ex: string example = “I see…”;
– Can initialize string in the same way as a normal class (Eight constructors)
Ex: string example = new string( “I see…” );
11
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.1: StringConstructor.cs
2 // Demonstrating string class constructors.
3 using System;
4
5 class StringConstructor
6 {
7 public static void Main()
8 {
9 string originalString, string1, string2,
10 string3, string4;
11 char[] characterArray =
12 { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
13
14 // string initialization
15 originalString = "Welcome to C# programming!";
16 string1 = originalString;
17 string2 = new string( characterArray );
18 string3 = new string( characterArray, 6, 3 );
19 string4 = new string( 'C', 5 );
Outline
StringConstructor.cs
(1 of 2)Assigns string literal to string reference originalString
Set string1 to have the same string literal as originalString
One-argument constructor creates a string that contains a copy of the
characters in the array argument
Three-argument constructor creates a string that contains a copy of partial
characters in the array argument
Two-argument constructor creates a string that contains the character argument repeated a
specified numbers of time
12
2006 Pearson Education, Inc. All rights reserved.
20
21 Console.WriteLine( "string1 = " + "\"" + string1 + "\"\n" +
22 "string2 = " + "\"" + string2 + "\"\n" +
23 "string3 = " + "\"" + string3 + "\"\n" +
24 "string4 = " + "\"" + string4 + "\"\n" );
25 } // end method Main
26 } // end class StringConstructor
string1 = "Welcome to C# programming!" string2 = "birth day" string3 = "day" string4 = "CCCCC"
Outline
StringConstructor.cs
(2 of 2)
13
2006 Pearson Education, Inc. All rights reserved.
Software Engineering Observation 16.1
In most cases, it is not necessary to make a copy of an existing string. All strings are immutable—their character contents cannot be changed after they are created. Also, if there are one or more references to a string (or any object for that matter), the object cannot be reclaimed by the garbage collector.
14
2006 Pearson Education, Inc. All rights reserved.
16.4 string Indexer, Length Property and CopyTo Method
•string indexer– Facilitates the retrieval of any character in the string
– Treats a string as an array of chars • Return the character at the specific position in the string
•Length property– Returns the length of the string
•CopyTo Method– Copies a specified number of characters into a char array
15
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.2: StringMethods.cs
2 // Using the indexer, property Length and method CopyTo
3 // of class string.
4 using System;
5
6 class StringMethods
7 {
8 public static void Main()
9 {
10 string string1;
11 char[] characterArray;
12
13 string1 = "hello there";
14 characterArray = new char[ 5 ];
15
16 // output string1
17 Console.WriteLine( "string1: \"" + string1 + "\"" );
18
19 // test Length property
20 Console.WriteLine( "Length of string1: " + string1.Length );
21
22 // loop through characters in string1 and display reversed
23 Console.Write( "The string reversed is: " );
24
25 for ( int i = string1.Length - 1; i >= 0; i-- )
26 Console.Write( string1[ i ] );
Outline
StringMethods.cs
(1 of 2)
Determine the number of characters in string1
Print the corresponding character at the indexer position of string1
16
2006 Pearson Education, Inc. All rights reserved.
27
28 // copy characters from string1 into characterArray
29 string1.CopyTo( 0, characterArray, 0, characterArray.Length );
30 Console.Write( "\nThe character array is: " );
31
32 for ( int i = 0; i < characterArray.Length; i++ )
33 Console.Write( characterArray[ i ] );
34
35 Console.WriteLine( "\n" );
36 } // end method Main
37 } // end class StringMethods
string1: "hello there" Length of string1: 11 The string reversed is: ereht olleh The character array is: hello
Outline
StringMethods.cs
(2 of 2)Determine the number of characters in the array
Print the corresponding character at the indexer
position of the array
Copy the characters from a string into a char array
17
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 16.1
Attempting to access a character that is outside a string’s bounds (i.e., an index less than 0 or an index greater than or equal to the string’s length) results in an IndexOutOfRangeException.
18
2006 Pearson Education, Inc. All rights reserved.
16.5 Comparing strings
• Comparing String objects– Method Equals or ==
• Determine if the strings are the same• Returns bool value• Uses a lexicographical comparison
– The integer Unicode value that represent each character in each string are compared
– Method CompareTo• Returns 0 if strings are equal• Returns negative value if the string invoked is less than the string that is
passed in• Returns positive value if the string invoked is greater than the string
that is passed in– Method StartsWith
• Determines if string instance starts with the string text passed to it as an argument
– Method EndWith• Determines if string instance ends with the string text passed to it as an
argument
19
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.3: StringCompare.cs
2 // Comparing strings
3 using System;
4
5 class StringCompare
6 {
7 public static void Main()
8 {
9 string string1 = "hello";
10 string string2 = "good bye";
11 string string3 = "Happy Birthday";
12 string string4 = "happy birthday";
13
14 // output values of four strings
15 Console.WriteLine( "string1 = \"" + string1 + "\"" +
16 "\nstring2 = \"" + string2 + "\"" +
17 "\nstring3 = \"" + string3 + "\"" +
18 "\nstring4 = \"" + string4 + "\"\n" );
19
20 // test for equality using Equals method
21 if ( string1.Equals( "hello" ) )
22 Console.WriteLine( "string1 equals \"hello\"" );
23 else
24 Console.WriteLine( "string1 does not equal \"hello\"" );
Outline
StringCompare.cs
(1 of 3)
Method Equals tests two strings for equality using
lexicographical comparison
20
2006 Pearson Education, Inc. All rights reserved.
25
26 // test for equality with ==
27 if ( string1 == "hello" )
28 Console.WriteLine( "string1 equals \"hello\"" );
29 else
30 Console.WriteLine( "string1 does not equal \"hello\"" );
31
32 // test for equality comparing case
33 if ( string.Equals( string3, string4 ) ) // static method
34 Console.WriteLine( "string3 equals string4" );
35 else
36 Console.WriteLine( "string3 does not equal string4" );
37
38 // test CompareTo
39 Console.WriteLine ( "\nstring1.CompareTo( string2 ) is " +
40 string1.CompareTo( string2 ) + "\n" +
41 "string2.CompareTo( string1 ) is " +
42 string2.CompareTo( string1 ) + "\n" +
43 "string1.CompareTo( string1 ) is " +
44 string1.CompareTo( string1 ) + "\n" +
45 "string3.CompareTo( string4 ) is " +
46 string3.CompareTo( string4 ) + "\n" +
47 "string4.CompareTo( string3 ) is " +
48 string4.CompareTo( string3 ) + "\n\n" );
49 } // end method Main
50 } // end class StringCompare
Outline
StringCompare.cs
(2 of 3)
Operator == also tests two strings for equality using
lexicographical comparison
static method Equals tests two strings for equality using lexicographical comparison
Method CompareTo compares string objects
21
2006 Pearson Education, Inc. All rights reserved.
Outline
StringCompare.cs
(3 of 3)
string1 = "hello" string2 = "good bye" string3 = "Happy Birthday" string4 = "happy birthday"
string1 equals "hello" string1 equals "hello" string3 does not equal string4
string1.CompareTo( string2 ) is 1 string2.CompareTo( string1 ) is -1 string1.CompareTo( string1 ) is 0 string3.CompareTo( string4 ) is 1 string4.CompareTo( string3 ) is -1
22
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.4: StringStartEnd.cs
2 // Demonstrating StartsWith and EndsWith methods.
3 using System;
4
5 class StringStartEnd
6 {
7 public static void Main()
8 {
9 string[] strings =
10 { "started", "starting", "ended", "ending" };
11
12 // test every string to see if it starts with "st"
13 for ( int i = 0; i < strings.Length; i++ )
14 if ( strings[ i ].StartsWith( "st" ) )
15 Console.WriteLine( "\"" + strings[ i ] + "\"" +
16 " starts with \"st\"" );
17
18 Console.WriteLine( "" );
Outline
StringStartEnd.cs
(1 of 2)
Method StartsWith determines if strings starts
with specified characters
23
2006 Pearson Education, Inc. All rights reserved.
19
20 // test every string to see if it ends with "ed"
21 for ( int i = 0; i < strings.Length; i++ )
22 if ( strings[ i ].EndsWith( "ed" ) )
23 Console.WriteLine( "\"" + strings[ i ] + "\"" +
24 " ends with \"ed\"" );
25
26 Console.WriteLine( "" );
27 } // end method Main
28 } // end class StringStartEnd "started" starts with "st" "starting" starts with "st"
"started" ends with "ed" "ended" ends with "ed"
Outline
StringStartEnd.cs
(2 of 2)
Method EndsWith determines if strings
ends with specified characters
24
2006 Pearson Education, Inc. All rights reserved.
16.6 Locating Characters and Substrings in strings
• Search for characters in string– Method IndexOf
• Returns the index of first occurrence of a character or substring; -1 if not found
– Method IndexOfAny• Same as IndexOf excepts it takes in an array of characters and
returns the index of the first occurrence of any of the characters in the array
– Method LastIndexOf• Returns the index of last occurrence of a character or substring; -1
if not found – Method LastIndexOfAny
• Same as LastIndexOf excepts it takes in an array of characters and returns the index of the last occurrence of any of the characters in the array
25
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.5: StringIndexMethods.cs
2 // Using string searching methods.
3 using System;
4
5 class StringIndexMethods
6 {
7 public static void Main()
8 {
9 string letters = "abcdefghijklmabcdefghijklm";
10 char[] searchLetters = { 'c', 'a', '$' };
11
12 // test IndexOf to locate a character in a string
13 Console.WriteLine( "First 'c' is located at index " +
14 letters.IndexOf( 'c' ) );
15 Console.WriteLine( "First 'a' starting at 1 is located at index " +
16 letters.IndexOf( 'a', 1 ) );
17 Console.WriteLine( "First '$' in the 5 positions starting at 3 " +
18 "is located at index " + letters.IndexOf( '$', 3, 5 ) );
19
20 // test LastIndexOf to find a character in a string
21 Console.WriteLine( "\nLast 'c' is located at index " +
22 letters.LastIndexOf( 'c' ) );
23 Console.WriteLine( "Last 'a' up to position 25 is located at " +
24 "index " + letters.LastIndexOf( 'a', 25 ) );
25 Console.WriteLine( "Last '$' in the 5 positions starting at 15 " +
26 "is located at index " + letters.LastIndexOf( '$', 15, 5 ) );
Outline
StringIndexMethods.cs
(1 of 4)
Method IndexOf finds the first occurrence of character in letters
Method LastIndexOf finds the last occurrence of character in letters
26
2006 Pearson Education, Inc. All rights reserved.
27
28 // test IndexOf to locate a substring in a string
29 Console.WriteLine( "\nFirst \"def\" is located at index " +
30 letters.IndexOf( "def" ) );
31 Console.WriteLine( "First \"def\" starting at 7 is located at " +
32 "index " + letters.IndexOf( "def", 7 ) );
33 Console.WriteLine( "First \"hello\" in the 15 positions " +
34 "starting at 5 is located at index " +
35 letters.IndexOf( "hello", 5, 15 ) );
36
37 // test LastIndexOf to find a substring in a string
38 Console.WriteLine( "\nLast \"def\" is located at index " +
39 letters.LastIndexOf( "def" ) );
40 Console.WriteLine( "Last \"def\" up to position 25 is located " +
41 "at index " + letters.LastIndexOf( "def", 25 ) );
42 Console.WriteLine( "Last \"hello\" in the 15 positions " +
43 "ending at 20 is located at index " +
44 letters.LastIndexOf( "hello", 20, 15 ) );
45
46 // test IndexOfAny to find first occurrence of character in array
47 Console.WriteLine( "\nFirst 'c', 'a' or '$' is " +
48 "located at index " + letters.IndexOfAny( searchLetters ) );
49 Console.WriteLine( "First 'c', 'a' or '$' starting at 7 is " +
50 "located at index " + letters.IndexOfAny( searchLetters, 7 ) );
51 Console.WriteLine( "First 'c', 'a' or '$' in the 5 positions " +
52 "starting at 7 is located at index " +
53 letters.IndexOfAny( searchLetters, 7, 5 ) );
Outline
StringIndexMethods.cs
(2 of 4)
Method IndexOf finds the first occurrence of substring in letters
Method LastIndexOf the finds last occurrence of substring in letters
Method IndexOfAny returns the index of the
first occurrence of any of the characters in the array
27
2006 Pearson Education, Inc. All rights reserved.
54
55 // test LastIndexOfAny to find last occurrence of character
56 // in array
57 Console.WriteLine( "\nLast 'c', 'a' or '$' is " +
58 "located at index " + letters.LastIndexOfAny( searchLetters ) );
59 Console.WriteLine( "Last 'c', 'a' or '$' up to position 1 is " +
60 "located at index " +
61 letters.LastIndexOfAny( searchLetters, 1 ) );
62 Console.WriteLine( "Last 'c', 'a' or '$' in the 5 positions " +
63 "ending at 25 is located at index " +
64 letters.LastIndexOfAny( searchLetters, 25, 5 ) );
65 } // end method Main
66 } // end class StringIndexMethods
Outline
StringIndexMethods.cs
(3 of 4)
Method LastIndexOfAny returns the index of the last
occurrence of any of the characters in the array
28
2006 Pearson Education, Inc. All rights reserved.
Outline
StringIndexMethods.cs
(4 of 4)
First 'c' is located at index 2 First 'a' starting at 1 is located at index 13 First '$' in the 5 positions starting at 3 is located at index -1 Last 'c' is located at index 15 Last 'a' up to position 25 is located at index 13 Last '$' in the 5 positions starting at 15 is located at index -1 First "def" is located at index 3 First "def" starting at 7 is located at index 16 First "hello" in the 15 positions starting at 5 is located at index -1 Last "def" is located at index 16 Last "def" up to position 25 is located at index 16 Last "hello" in the 15 positions ending at 20 is located at index -1 First 'c', 'a' or '$' is located at index 0 First 'c', 'a' or '$' starting at 7 is located at index 13 First 'c', 'a' or '$' in the 5 positions starting at 7 is located at index -1 Last 'c', 'a' or '$' is located at index 15 Last 'c', 'a' or '$' up to position 1 is located at index 0 Last 'c', 'a' or '$' in the 5 positions ending at 25 is located at index -1
29
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 16.2
In the overloaded methods LastIndexOf and LastIndexOfAny that take three parameters, the second argument must be greater than or equal to the third. This might seem counterintuitive, but remember that the search moves from the end of the string toward the start of the string.
30
2006 Pearson Education, Inc. All rights reserved.
16.7 Extracting Substrings from strings
• Method Substring– Creates and returns a new string by copying part of an
existing string
31
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.6: SubString.cs
2 // Demonstrating the string Substring method.
3 using System;
4
5 class SubString
6 {
7 public static void Main()
8 {
9 string letters = "abcdefghijklmabcdefghijklm";
10
11 // invoke Substring method and pass it one parameter
12 Console.WriteLine( "Substring from index 20 to end is \"" +
13 letters.Substring( 20 ) + "\"" );
14
15 // invoke Substring method and pass it two parameters
16 Console.WriteLine( "Substring from index 0 of length 6 is \"" +
17 letters.Substring( 0, 6 ) + "\"" );
18 } // end method Main
19 } // end class SubString Substring from index 20 to end is "hijklm" Substring from index 0 of length 6 is "abcdef"
Outline
SubString.cs
Beginning at index 20, copy all the characters
from letters
Extract the characters from index 0 to 6 from letters
32
2006 Pearson Education, Inc. All rights reserved.
16.8 Concatenating Strings
• Method Concat or +– Returns a new string containing the combined
characters from both original strings
33
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.7: SubConcatenation.cs
2 // Demonstrating string class Concat method.
3 using System;
4
5 class StringConcatenation
6 {
7 public static void Main()
8 {
9 string string1 = "Happy ";
10 string string2 = "Birthday";
11
12 Console.WriteLine( "string1 = \"" + string1 + "\"\n" +
13 "string2 = \"" + string2 + "\"" );
14 Console.WriteLine(
15 "\nResult of string.Concat( string1, string2 ) = " +
16 string.Concat( string1, string2 ) );
17 Console.WriteLine( "string1 after concatenation = " + string1 );
18 } // end method Main
19 } // end class StringConcatenation
string1 = "Happy " string2 = "Birthday" Result of string.Concat( string1, string2 ) = Happy Birthday string1 after concatenation = Happy
Outline
SubConcatenation.cs
Concatenate string2 to string1
However, string1 is not modified by method Concat
34
2006 Pearson Education, Inc. All rights reserved.
16.9 Miscellaneous string Methods
• Miscellaneous string methods– Method Replace
• Returns a new string replacing every occurrence of the specified phrase with another phrase in the string
– Method ToLower• Returns a new lower cased version of the string
– Method ToUpper• Returns a new upper cased version of the string
– Method Trim• Remove all white space characters from the string
35
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.8: StringMethods2.cs
2 // Demonstrating string methods Replace, ToLower, ToUpper, Trim,
3 // and ToString.
4 using System;
5
6 class StringMethods2
7 {
8 public static void Main()
9 {
10 string string1 = "cheers!";
11 string string2 = "GOOD BYE ";
12 string string3 = " spaces ";
13
14 Console.WriteLine( "string1 = \"" + string1 + "\"\n" +
15 "string2 = \"" + string2 + "\"\n" +
16 "string3 = \"" + string3 + "\"" );
17
18 // call method Replace
19 Console.WriteLine(
20 "\nReplacing \"e\" with \"E\" in string1: \"" +
21 string1.Replace( 'e', 'E' ) + "\"" );
22
23 // call ToLower and ToUpper
24 Console.WriteLine( "\nstring1.ToUpper() = \"" +
25 string1.ToUpper() + "\"\nstring2.ToLower() = \"" +
26 string2.ToLower() + "\"" );
Outline
StringMethods2.cs
(1 of 2)
Use method Replace to return a copy of string1 in which every occurrence of ‘e’ is replaced with
‘E’
Use method ToUpper to return a copy of string1 in which every character is uppercase
Use method ToLower to return a copy of string2 in which every character is lowercase
36
2006 Pearson Education, Inc. All rights reserved.
27
28 // call Trim method
29 Console.WriteLine( "\nstring3 after trim = \"" +
30 string3.Trim() + "\"" );
31
32 Console.WriteLine( "\nstring1 = \"" + string1 + "\"" );
33 } // end method Main
34 } // end class StringMethods2 string1 = "cheers!" string2 = "GOOD BYE " string3 = " spaces " Replacing "e" with "E" in string1: "chEErs!" string1.ToUpper() = "CHEERS!" string2.ToLower() = "good bye " string3 after trim = "spaces" string1 = "cheers!"
Outline
StringMethods2.cs
(2 of 2)
Use method Trim to return a copy of
string3 in which whitespace is eliminated
37
2006 Pearson Education, Inc. All rights reserved.
16.10 Class StringBuilder
• Class StringBuilder– Used to create and manipulate dynamic string information
– Every StringBuilder can store the number of characters specified by its capacity
• Exceeding the capacity of a StringBuilder makes the capacity expand to accommodate the additional characters
• The default initial capacity is 16 characters
– 6 overloaded constructors
38
2006 Pearson Education, Inc. All rights reserved.
Performance Tip 16.2
Objects of class string are immutable (i.e., constant strings), whereas object of class StringBuilder are mutable. C# can perform certain optimizations involving strings (such as the sharing of one string among multiple references), because it knows these objects will not change.
39
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.9: StringBuilderConstructor.cs
2 // Demonstrating StringBuilder class constructors.
3 using System;
4 using System.Text;
5
6 class StringBuilderConstructor
7
8 public static void Main()
9 {
10 StringBuilder buffer1, buffer2, buffer3;
11
12 buffer1 = new StringBuilder();
13 buffer2 = new StringBuilder( 10 );
14 buffer3 = new StringBuilder( "hello" );
15
16 Console.WriteLine( "buffer1 = \"" + buffer1 + "\"" );
17 Console.WriteLine( "buffer2 = \"" + buffer2 + "\"" );
18 Console.WriteLine( "buffer3 = \"" + buffer3 + "\"" );
19 } // end method Main
20 } // end class StringBuilderConstructor
buffer1 = "" buffer2 = "" buffer3 = "hello"
Outline
StringBuilderConstructor.cs
No-argument constructor creates empty StringBuilder with
capacity of 16 characters
One-argument constructor creates empty StringBuilder with
capacity of specified (10) characters
One-argument constructor creates StringBuilder
with string “hello” and capacity of 16 characters
Namespace for class StringBuilder
40
2006 Pearson Education, Inc. All rights reserved.
16.11 Length and Capacity Properties, EnsureCapacity Method and Indexer of Class StringBuilder
•Length Property– Return number of characters currently in the StringBuilder
• Capacity Property– Return number of characters that the StringBuilder
can store without allocating more memory
•EnsureCapacity Method– Reduce the number of times the StringBuilder’s
capacity can be increased
• Indexers is like that of string
41
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.10: StringBuilderFeatures.cs
2 // Demonstrating some features of class StringBuilder.
3 using System;
4 using System.Text;
5
6 class StringBuilderFeatures
7 {
8 public static void Main()
9 {
10 StringBuilder buffer =
11 new StringBuilder( "Hello, how are you?" );
12
13 // use Length and Capacity properties
14 Console.WriteLine( "buffer = " + buffer +
15 "\nLength = " + buffer.Length +
16 "\nCapacity = " + buffer.Capacity );
17
18 buffer.EnsureCapacity( 75 ); // ensure a capacity of at least 75
19 Console.WriteLine( "\nNew capacity = " +
20 buffer.Capacity );
21
22 // truncate StringBuilder by setting Length property
23 buffer.Length = 10;
24 Console.Write( "\nNew length = " +
25 buffer.Length + "\nbuffer = " );
Outline
StringBuilderFeatures.cs
(1 of 2)Property Length returns the number of characters currently in the buffer
Property Capacity returns the number of characters that buffer can store
without allocating more memory
Use method EnsureCapacity to set capacity to 75
Use property Length to set length to 10
Create a new StringBuilder
42
2006 Pearson Education, Inc. All rights reserved.
26
27 // use StringBuilder indexer
28 for ( int i = 0; i < buffer.Length; i++ )
29 Console.Write( buffer[ i ] );
30
31 Console.WriteLine( "\n" );
32 } // end method Main
33 } // end class StringBuilderFeatures
buffer = Hello, how are you? Length = 19 Capacity = 32 New capacity = 75 New length = 10 buffer = Hello, how
Outline
StringBuilderFeatures.cs
(2 of 2)
Property Length returns the number of characters currently in the buffer
Print corresponding character to the indexer’s
position in buffer
43
2006 Pearson Education, Inc. All rights reserved.
Common Programming Error 16.3
Assigning null to a string reference can lead to logic errors if you attempt to compare null to an empty string. The keyword null is a value that represents a null reference (i.e., a reference that does not refer to an object), not an empty string (which is a string object that is of length 0 and contains no characters).
44
2006 Pearson Education, Inc. All rights reserved.
16.12 Append and AppendFormat Methods of Class StringBuilder
• Method Append– Appends the string representation to the end the StringBuilder
• Method AppendFormat– Converts a string to a specified format, then appends it
to the StringBuilder
45
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.11: StringBuilderAppend.cs
2 // Demonstrating StringBuilder Append methods.
3 using System;
4 using System.Text;
5
6 class StringBuilderAppend
7 {
8 public static void Main( string[] args )
9 {
10 object objectValue = "hello";
11 string stringValue = "good bye";
12 char[] characterArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
13 bool booleanValue = true;
14 char characterValue = 'Z';
15 int integerValue = 7;
16 long longValue = 1000000;
17 float floatValue = 2.5F; // F suffix indicates that 2.5 is a float
18 double doubleValue = 33.333;
19 StringBuilder buffer = new StringBuilder();
Outline
StringBuilderAppend.cs
(1 of 2)
46
2006 Pearson Education, Inc. All rights reserved.
20
21 // use method Append to append values to buffer
22 buffer.Append( objectValue );
23 buffer.Append( " " );
24 buffer.Append( stringValue );
25 buffer.Append( " " );
26 buffer.Append( characterArray );
27 buffer.Append( " " );
28 buffer.Append( characterArray, 0, 3 );
29 buffer.Append( " " );
30 buffer.Append( booleanValue );
31 buffer.Append( " " );
32 buffer.Append( characterValue );
33 buffer.Append( " " );
34 buffer.Append( integerValue );
35 buffer.Append( " " );
36 buffer.Append( longValue );
37 buffer.Append( " " );
38 buffer.Append( floatValue );
39 buffer.Append( " " );
40 buffer.Append( doubleValue );
41
42 Console.WriteLine( "buffer = " + buffer.ToString() + "\n" );
43 } // end method Main
44 } // end class StringBuilderAppend buffer = hello good bye abcdef abc True Z 7 1000000 2.5 33.333
Outline
StringBuilderAppend.cs
(2 of 2)
Append boolean, char, int, long, float and double
Append string “hello” to StringBuilder
Append string “good bye”
Append “a b c d e f”
Append “a b c”
Append a space character to StringBuilder
Print out results
47
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.12: StringBuilderAppendFormat.cs
2 // Demonstrating method AppendFormat.
3 using System;
4 using System.Text;
5
6 class StringBuilderAppendFormat
7 {
8 public static void Main( string[] args )
9 {
10 StringBuilder buffer = new StringBuilder();
11 string string1, string2;
12
13 // formatted string
14 string1 = "This {0} costs: {1:C}.\n";
15
16 // string1 argument array
17 object[] objectArray = new object[ 2 ];
18
19 objectArray[ 0 ] = "car";
20 objectArray[ 1 ] = 1234.56;
21
22 // append to buffer formatted string with argument
23 buffer.AppendFormat( string1, objectArray );
Outline
StringBuilderAppendFormat.cs
(1 of 2)
String literal that contains formatting information
string1’s arguments
Combine the string literal and the arguments together
48
2006 Pearson Education, Inc. All rights reserved.
24
25 // formatted string
26 string2 = "Number:{0:d3}.\n" +
27 "Number right aligned with spaces:{0, 4}.\n" +
28 "Number left aligned with spaces:{0, -4}.";
29
30 // append to buffer formatted string with argument
31 buffer.AppendFormat( string2, 5 );
32
33 // display formatted strings
34 Console.WriteLine( buffer.ToString() );
35 } // end method Main
36 } // end class StringBuilderAppendFormat
This car costs: $1,234.56. Number:005. Number right aligned with spaces: 5. Number left aligned with spaces:5 .
Outline
StringBuilderAppendFormat.cs
(2 of 2)
Another string literal that contains formatting information
Combine the string literal and the argument together
49
2006 Pearson Education, Inc. All rights reserved.
16.13 Insert, Remove and Replace Methods of Class StringBuilder
• Method Insert – Allow various types of data to be inserted at any position
• Method Remove– Delete any portion of StringBuilder
• Method Replace– Searches for a specified string or character and substitutes
another string or character in its place
50
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.13: StringBuilderInsertRemove.cs
2 // Demonstrating methods Insert and Remove of the
3 // StringBuilder class.
4 using System;
5 using System.Text;
6
7 class StringBuilderInsertRemove
8 {
9 public static void Main()
10 {
11 object objectValue = "hello";
12 string stringValue = "good bye";
13 char[] characterArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
14 bool booleanValue = true;
15 char characterValue = 'K';
16 int integerValue = 7;
17 long longValue = 10000000;
18 float floatValue = 2.5F; // F suffix indicates that 2.5 is a float
19 double doubleValue = 33.333;
20 StringBuilder buffer = new StringBuilder();
Outline
StringBuilderInsertRemove.cs
(1 of 3)
51
2006 Pearson Education, Inc. All rights reserved.
21
22 // insert values into buffer
23 buffer.Insert( 0, objectValue );
24 buffer.Insert( 0, " " );
25 buffer.Insert( 0, stringValue );
26 buffer.Insert( 0, " " );
27 buffer.Insert( 0, characterArray );
28 buffer.Insert( 0, " " );
29 buffer.Insert( 0, booleanValue );
30 buffer.Insert( 0, " " );
31 buffer.Insert( 0, characterValue );
32 buffer.Insert( 0, " " );
33 buffer.Insert( 0, integerValue );
34 buffer.Insert( 0, " " );
35 buffer.Insert( 0, longValue );
36 buffer.Insert( 0, " " );
37 buffer.Insert( 0, floatValue );
38 buffer.Insert( 0, " " );
39 buffer.Insert( 0, doubleValue );
40 buffer.Insert( 0, " " );
41
42 Console.WriteLine( "buffer after Inserts: \n" + buffer + "\n" );
43
44 buffer.Remove( 10, 1 ); // delete 2 in 2.5
45 buffer.Remove( 4, 4 ); // delete .333 in 33.333
Outline
StringBuilderInsertRemove.cs
(2 of 3)Use method Insert to insert data in beginning of StringBuilder
Use method Remove to remove character from index 10 in
StringBuilder
Remove characters from indices 4 through 7
52
2006 Pearson Education, Inc. All rights reserved.
46
47 Console.WriteLine( "buffer after Removes:\n" + buffer.ToString() );
48 } // end method Main
49 } // end class StringBuilderInsertRemove
buffer after Inserts: 33.333 2.5 10000000 7 K True abcdef good bye hello buffer after Removes: 33 .5 10000000 7 K True abcdef good bye hello
Outline
StringBuilderInsertRemove.cs
(3 of 3)
53
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.14: StringBuilderReplace.cs
2 // Demonstrating method Replace.
3 using System;
4 using System.Text;
5
6 class StringBuilderReplace
7 {
8 public static void Main()
9 {
10 StringBuilder builder1 =
11 new StringBuilder( "Happy Birthday Jane" );
12 StringBuilder builder2 =
13 new StringBuilder( "good bye greg" );
14
15 Console.WriteLine( "Before replacements:\n" +
16 builder1.ToString() + "\n" + builder2.ToString() );
17
18 builder1.Replace( "Jane", "Greg" );
19 builder2.Replace( 'g', 'G', 0, 5 );
Outline
StringBuilderReplace.cs
(1 of 2)
Replace “Jane” with “Greg” in builder1
Replace “g” with “G” in the first 5 characters of
builder2
54
2006 Pearson Education, Inc. All rights reserved.
20
21 Console.WriteLine( "\nAfter replacements:\n" +
22 builder1.ToString() + "\n" + builder2.ToString() );
23 } // end method Main
24 } // end class StringBuilderReplace
Before Replacements: Happy Birthday Jane good bye greg After replacements: Happy Birthday Greg Good bye greg
Outline
StringBuilderReplace.cs
(2 of 2)
55
2006 Pearson Education, Inc. All rights reserved.
16.14 Char Methods
•Char– Simple types (including char) are structs
• Represents value types– structs derive from ValueType
– Most methods are static• IsDigit• IsLetter• IsLetterOrDigit• IsLower• IsUpper• ToLower• ToUpper• IsPunctuation• IsSymbol
56
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.15: StaticCharMethods.cs
2 // Demonstrates static character testing methods
3 // from Char struct
4 using System;
5 using System.Windows.Forms;
6
7 public partial class StaticCharMethodsForm : Form
8 {
9 // default constructor
10 public StaticCharMethodsForm()
11 {
12 InitializeComponent();
13 } // end constructor
14
15 // handle analyzeButton_Click
16 private void analyzeButton_Click( object sender, EventArgs e )
17 {
18 // convert string entered to type char
19 char character = Convert.ToChar( inputTextBox.Text );
20 string output;
Outline
StaticCharMethods.cs
(1 of 3)
Convert the user’s input to a char
57
2006 Pearson Education, Inc. All rights reserved.
21
22 output = "is digit: " +
23 Char.IsDigit( character ) + "\r\n";
24 output += "is letter: " +
25 Char.IsLetter( character ) + "\r\n";
26 output += "is letter or digit: " +
27 Char.IsLetterOrDigit( character ) + "\r\n";
28 output += "is lower case: " +
29 Char.IsLower( character ) + "\r\n";
30 output += "is upper case: " +
31 Char.IsUpper( character ) + "\r\n";
32 output += "to upper case: " +
33 Char.ToUpper( character ) + "\r\n";
34 output += "to lower case: " +
35 Char.ToLower( character ) + "\r\n";
36 output += "is punctuation: " +
37 Char.IsPunctuation( character ) + "\r\n";
38 output += "is symbol: " + Char.IsSymbol( character );
39 outputTextBox.Text = output;
40 } // end method analyzeButton_Click
41 } // end class StaticCharMethodsForm
Outline
StaticCharMethods.cs
(2 of 3)
Determine whether character is a digit
Determine whether character is lowercase and uppercase, respectively
Convert character to its uppercase and lowercase, respectively
Determine whether character is a letter
Determine whether character is a letter or a digit
Determine whether character is a letter or a digit
Determine whether character is a punctuation
Determine whether character is a symbol
58
2006 Pearson Education, Inc. All rights reserved.
Outline
StaticCharMethods.cs
(3 of 3)
(a) (b) (c)
(d) (e)
59
2006 Pearson Education, Inc. All rights reserved.
16.15 Card Shuffling and Dealing Simulation
• This example shows how strings could be used in programs
60
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.16: Card.cs
2 // Stores suit and face information on each card.
3 using System;
4
5 public class Card
6 {
7 private string face;
8 private string suit;
9
10 public Card( string faceValue, string suitValue )
11 {
12 face = faceValue;
13 suit = suitValue;
14 } // end constructor
15
16 public override string ToString()
17 {
18 return face + " of " + suit;
19 } // end method ToString
20 } // end class Card
Outline
Card.cs Fields that
represents a card
61
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.17: DeckForm.cs
2 // Simulating card shuffling and dealing.
3 using System;
4 using System.Windows.Forms;
5
6 public partial class DeckForm : Form
7 {
8 private Card[] deck = new Card[ 52 ]; // deak of 52 cards
9 private int currentCard; // count which card was just dealt
10
11 // default constructor
12 public DeckForm()
13 {
14 // Required for Windows Form Designer support
15 InitializeComponent();
16 } // end constructor
17
18 // handles form at load time
19 private void DeckForm_Load( object sender, EventArgs e )
20 {
21 string[] faces = { "Ace", "Deuce", "Three", "Four", "Five",
22 "Six", "Seven", "Eight", "Nine", "Ten",
23 "Jack", "Queen", "King" };
24 string[] suits = { "Hearts", "Diamonds", "Clubs", "Spades" };
25
26 currentCard = -1; // no cards have been dealt
Outline
DeckForm.cs
(1 of 5)
An array of Cards to represent a deck of cards
An array of strings to represent the many faces of a card
An array of strings to represent the many suits of a card
62
2006 Pearson Education, Inc. All rights reserved.
27
28 // initialize deck
29 for ( int i = 0; i < deck.Length; i++ )
30 deck[ i ] = new Card( faces[ i % 13 ], suits[ i / 13 ] );
31 } // end method DeckForm_Load
32
33 // handles dealButton Click
34 private void dealButton_Click( object sender, EventArgs e )
35 {
36 Card dealt = DealCard();
37
38 // if dealt card is null, then no cards left
39 // player must shuffle cards
40 if ( dealt != null )
41 {
42 displayLabel.Text = dealt.ToString();
43 statusLabel.Text = "Card #: " + currentCard;
44 } // end if
45 else
46 {
47 displayLabel.Text = "NO MORE CARDS TO DEAL";
48 statusLabel.Text = "Shuffle cards to continue";
49 } // end else
50 } // end method dealButton_Click
Outline
DeckForm.cs
(2 of 5)
Assign a face and a suit to every card of the deck
Store the dealt card
Display the dealt card
Notify user that no cards remain
63
2006 Pearson Education, Inc. All rights reserved.
51
52 // shuffle cards
53 private void Shuffle()
54 {
55 Random randomNumber = new Random();
56 Card temporaryValue;
57
58 currentCard = -1;
59
60 // swap each card with randomly selected card (0-51)
61 for ( int i = 0; i < deck.Length; i++ )
62 {
63 int j = randomNumber.Next( 52 );
64
65 // swap cards
66 temporaryValue = deck[ i ];
67 deck[ i ] = deck[ j ];
68 deck[ j ] = temporaryValue;
69 } // end for
70
71 dealButton.Enabled = true; // shuffled deck can now deal cards
72 } // end method Shuffle
Outline
DeckForm.cs
(3 of 5)
Create a Random object to make shuffle random
Swap cards for shuffling
64
2006 Pearson Education, Inc. All rights reserved.
73
74 // deal a card if the deck is not empty
75 private Card DealCard()
76 {
77 // if there is a card to deal then deal it
78 // otherwise signal that cards need to be shuffled by
79 // disabling dealButton and returning null
80 if ( currentCard + 1 < deck.Length )
81 {
82 currentCard++; // increment count
83 return deck[ currentCard ]; // return new card
84 } // end if
85 else
86 {
87 dealButton.Enabled = false; // empty deck cannot deal cards
88 return null; // do not return a card
89 } // end else
90 } // end method DealCard
91
92 // handles shuffleButton Click
93 private void shuffleButton_Click( object sender, EventArgs e )
94 {
95 displayLabel.Text = "SHUFFLING...";
96 Shuffle();
97 displayLabel.Text = "DECK IS SHUFFLED";
98 } // end method shuffleButton_Click
99 } // end class DeckForm
Outline
DeckForm.cs
(4 of 5)
Shuffle cards
65
2006 Pearson Education, Inc. All rights reserved.
Outline
DeckForm.cs
(5 of 5)
(a)
(b)
(c)
(d)
66
2006 Pearson Education, Inc. All rights reserved.
16.16 Regular Expressions and Class Regex
•Regex Class– From namespace System.Text.RegularExpressions
– Represents an immutable regular expression• Specially formatted strings
– Method Match • Returns an object of class Match that represents a single
regular expression match
– Method Matches• Finds all matches of a regular expression in a string and
returns an object of the class MatchCollection object containing all the Matches
67
2006 Pearson Education, Inc. All rights reserved.
Fig. 16.18 | Character classes.
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
68
2006 Pearson Education, Inc. All rights reserved.
16.16.1 Regular Expression Example
• The dot character “.” matches any single character except a newline character
– When the dot character is followed by an asterisk, the regular expression matches any number of unspecified character except newlines
• Range of characters are represented by placing a dash between two characters
• Can specify that pattern should match anything other than the characters in the brackets using “^”
– Ex: [^4] matches any non-digit and digits other than 4
• All qualifiers are greedy– Will match as many occurrences of the pattern as possible– If qualifier is followed by a question mark, it becomes lazy
• Will match as few occurrences as possible
69
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.19: RegexMatches.cs
2 // Demonstrating Class Regex.
3 using System;
4 using System.Text.RegularExpressions;
5
6 class RegexMatches
7 {
8 public static void Main()
9 {
10 // create regular expression
11 Regex expression =
12 new Regex( @"J.*\d[0-35-9]-\d\d-\d\d" );
13
14 string string1 = "Jane's Birthday is 05-12-75\n" +
15 "Dave's Birthday is 11-04-68\n" +
16 "John's Birthday is 04-28-73\n" +
17 "Joe's Birthday is 12-17-77";
18
19 // match regular expression to string and
20 // print out all matches
21 foreach ( Match myMatch in expression.Matches( string1 ) )
22 Console.WriteLine( myMatch );
23 } // end method Main
24 } // end class RegexMatches
Jane's Birthday is 05-12-75 Joe's Birthday is 12-17-77
Outline
RegexMatches.cs
Using System.Text.RegularExpressions namespace for finding patterns in the text
Create a Regex object with a regular expression string
string1 used for finding patterns
Find and print out all matches
70
2006 Pearson Education, Inc. All rights reserved.
Fig. 16.20 | Quantifiers used in regular expressions.
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.
71
2006 Pearson Education, Inc. All rights reserved.
16.16.2 Validating User Input with Regular Expressions
•Match Property Success– Indicates whether there was a match
• "|" matches the expression to its left or to its right
• Parentheses can be used to group parts of a regular expression
• Quantifiers may be applied to patterns enclosed in parentheses to create more complex regular expressions
72
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.21: Validate.cs
2 // Validate user information using regular expressions.
3 using System;
4 using System.Text.RegularExpressions;
5 using System.Windows.Forms;
6
7 public partial class ValidateForm : Form
8 {
9 // default constructor
10 public ValidateForm()
11 {
12 InitializeComponent();
13 } // end constructor
14
15 // handles OkButton Click event
16 private void okButton_Click( object sender, EventArgs e )
17 {
18 // ensures no TextBoxes are empty
19 if ( lastNameTextBox.Text == "" || firstNameTextBox.Text == "" ||
20 addressTextBox.Text == "" || cityTextBox.Text == "" ||
21 stateTextBox.Text == "" || zipCodeTextBox.Text == "" ||
22 phoneTextBox.Text == "" )
23 {
24 // display popup box
25 MessageBox.Show( "Please fill in all fields", "Error",
26 MessageBoxButtons.OK, MessageBoxIcon.Error );
27 lastNameTextBox.Focus(); // set focus to lastNameTextBox
28 return;
29 } // end if
Outline
Validate.cs
(1 of 7)
73
2006 Pearson Education, Inc. All rights reserved.
30
31 // if last name format invalid show message
32 if ( !Regex.Match( lastNameTextBox.Text,
33 "^[A-Z][a-zA-Z]*$" ).Success )
34 {
35 // last name was incorrect
36 MessageBox.Show( "Invalid last name", "Message",
37 MessageBoxButtons.OK, MessageBoxIcon.Error );
38 lastNameTextBox.Focus();
39 return;
40 } // end if
41
42 // if first name format invalid show message
43 if ( !Regex.Match( firstNameTextBox.Text,
44 "^[A-Z][a-zA-Z]*$" ).Success )
45 {
46 // first name was incorrect
47 MessageBox.Show( "Invalid first name", "Message",
48 MessageBoxButtons.OK, MessageBoxIcon.Error );
49 firstNameTextBox.Focus();
50 return;
51 } // end if
Outline
Validate.cs
(2 of 7)
The Success property indicates whether the first argument matches the
pattern from the second argument
74
2006 Pearson Education, Inc. All rights reserved.
52
53 // if address format invalid show message
54 if ( !Regex.Match( addressTextBox.Text,
55 @"^[0-9]+\s+([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$" ).Success )
56 {
57 // address was incorrect
58 MessageBox.Show( "Invalid address", "Message",
59 MessageBoxButtons.OK, MessageBoxIcon.Error );
60 addressTextBox.Focus();
61 return;
62 } // end if
63
64 // if city format invalid show message
65 if ( !Regex.Match( cityTextBox.Text,
66 @"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$" ).Success )
67 {
68 // city was incorrect
69 MessageBox.Show( "Invalid city", "Message",
70 MessageBoxButtons.OK, MessageBoxIcon.Error );
71 cityTextBox.Focus();
72 return;
73 } // end if
Outline
Validate.cs
(3 of 7)
The Success property indicates whether the first argument matches the
pattern from the second argument
75
2006 Pearson Education, Inc. All rights reserved.
74
75 // if state format invalid show message
76 if ( !Regex.Match( stateTextBox.Text,
77 @"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$" ).Success )
78 {
79 // state was incorrect
80 MessageBox.Show( "Invalid state", "Message",
81 MessageBoxButtons.OK, MessageBoxIcon.Error );
82 stateTextBox.Focus();
83 return;
84 } // end if
85
86 // if zip code format invalid show message
87 if ( !Regex.Match( zipCodeTextBox.Text, @"^\d{5}$" ).Success )
88 {
89 // zip was incorrect
90 MessageBox.Show( "Invalid zip code", "Message",
91 MessageBoxButtons.OK, MessageBoxIcon.Error );
92 zipCodeTextBox.Focus();
93 return;
94 } // end if
Outline
Validate.cs
(4 of 7)
The Success property indicates whether the first argument matches the
pattern from the second argument
76
2006 Pearson Education, Inc. All rights reserved.
95
96 // if phone number format invalid show message
97 if ( !Regex.Match( phoneTextBox.Text,
98 @"^[1-9]\d{2}-[1-9]\d{2}-\d{4}$" ).Success )
99 {
100 // phone number was incorrect
101 MessageBox.Show( "Invalid phone number", "Message",
102 MessageBoxButtons.OK, MessageBoxIcon.Error );
103 phoneTextBox.Focus();
104 return;
105 } // end if
106
107 // information is valid, signal user and exit application
108 this.Hide(); // hide main window while MessageBox displays
109 MessageBox.Show( "Thank You!", "Information Correct",
110 MessageBoxButtons.OK, MessageBoxIcon.Information );
111 Application.Exit();
112 } // end method okButton_Click
113 } // end class ValidateForm
Outline
Validate.cs
(5 of 7)The Success property indicates whether the first argument matches the
pattern from the second argument
Hides the form
Terminate program
77
2006 Pearson Education, Inc. All rights reserved.
Outline
Validate.cs
(6 of 7)
(a)
(b)
78
2006 Pearson Education, Inc. All rights reserved.
Outline
Validate.cs
(7 of 7)
(c)
(d)
79
2006 Pearson Education, Inc. All rights reserved.
16.16.3 Regex Methods Replace and Split
• Method Replace – Replaces text in a string with new text wherever the
original string matches a regular expression
• Method Split– Divides a string into several substrings
– The original string is broken at delimiters that match a specified regular expression
– Returns an array containing the substrings
80
2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 16.22: RegexSubstitution.cs
2 // Using Regex method Replace.
3 using System;
4 using System.Text.RegularExpressions;
5
6 class RegexSubstitution
7 {
8 public static void Main()
9 {
10 string testString1 =
11 "This sentence ends in 5 stars *****";
12 string output = "";
13 string testString2 = "1, 2, 3, 4, 5, 6, 7, 8";
14 Regex testRegex1 = new Regex( @"\d" );
15 string[] result;
16
17 Console.WriteLine( "Original string: " +
18 testString1 );
19 testString1 = Regex.Replace( testString1, @"\*", "^" );
20 Console.WriteLine( "^ substituted for *: " + testString1 );
21 testString1 = Regex.Replace( testString1, "stars",
22 "carets" );
23 Console.WriteLine( "\"carets\" substituted for \"stars\": " +
24 testString1 );
25 Console.WriteLine( "Every word replaced by \"word\": " +
26 Regex.Replace( testString1, @"\w+", "word" ) );
27 Console.WriteLine( "\nOriginal string: " + testString2 );
28 Console.WriteLine( "Replace first 3 digits by \"digit\": " +
29 testRegex1.Replace( testString2, "digit", 3 ) );
30 Console.Write( "string split at commas [" );
Outline
RegexSubstitution.cs
(1 of 2)
Create a Regex object
strings used for finding patterns
Replaces “*” with “^” in testString1
Replaces “stars” with “carets” in
testString1
Replaces every word with “word”
Replaces the first 3 digits with “digit”
81
2006 Pearson Education, Inc. All rights reserved.
31
32 result = Regex.Split( testString2, @",\s" );
33
34 foreach ( string resultString in result )
35 output += "\"" + resultString + "\", ";
36
37 // Delete ", " at the end of output string
38 Console.WriteLine( output.Substring( 0, output.Length - 2 ) + "]" );
39 } // end method Main
40 } // end class RegexSubstitution Original string: This sentence ends in 5 stars ***** ^ substituted for *: This sentence ends in 5 stars ^^^^^ "carets" substituted for "stars": This sentence ends in 5 carets ^^^^^ Every word replaced by "word": word word word word word word ^^^^^
Original string: 1, 2, 3, 4, 5, 6, 7, 8 Replace first 3 digits by "digit": digit, digit, digit, 4, 5, 6, 7, 8 string split at commas ["1", "2", "3", "4", "5", "6", "7", "8"]
Outline
RegexSubstitution.cs
(2 of 2)
Split the string at commas and have each substring as an element of a string array