Download presentation
Presentation is loading. Please wait.
1
Strings and Characters
Many slides modified by Prof. L. Lilien (even many without explicit message). Slides added by L.Lilien are © Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., ed) request.
2
<------ END of READ ON YOUR OWN 18.4-18.10-- ------
Outline (ed.3) Introduction Fundamentals of Characters and Strings String Constructors READ ON YOUR OWN – String Indexer, Length Property and CopyTo Method Comparing Strings SKIP String Method GetHashCode Locating Characters and Substrings in Strings Extracting Substrings from Strings Concatenating Strings Miscellaneous String Methods < END of READ ON YOUR OWN (a part) Class StringBuilder (just signaled: how different, why needed) SKIP most of 18.10, > Length and Capacity Properties, EnsureCapacity Method and Indexer of Class StringBuilder Append and AppendFormat Methods of Class StringBuilder Insert, Remove and Replace Methods of Class StringBuilder Char Methods SKIP > >> SELF-STUDY<< Card Shuffling and Dealing Simulation Regular Expressions and Class Regex Regular Expression Example Validating User Input with Regular Expressions Regex methods Replace and Split
3
18.1 Introduction String and character processing capabilities – useful in: Text editors Word processors … Simple string uses shown in previous chapters Now: expanding on string and character processing -- capabilities of .NET Framework Class Library Class String Type char Class StringBuilder – just signaled - Classes Regex and Match – not covered Slide modified by L. Lilien
4
18.2 Fundamentals of Characters and Strings
Importance of characters: Are fundamental building blocks of C# source code Characters – represented as: 1) Normal character (a b c … … # …) 2) Character constants = character represented by character code Character code is an integer value E.g., (in ASCII): character constant ‘r’ represented by character code 114 character constant ‘R’ represented by character code 82 character constant ‘$’ represented by character code 36 Slide modified by L. Lilien
5
18.2 Fundamentals of Characters and Strings
Character sets ASCII character set Represents English characters on many computers Details - see Appendix F (ed.3) Unicode character set International character set Includes ASCII character set Details - see Appendix G (ed.3) Slide modified by L. Lilien
6
18.2 Fundamentals of Characters and Strings
A series of characters treated as a single unit E.g. “this is a string” Object of class String In System namespace, i.e. System.String String constants = string literals = literal strings E.g., “this is a string constant” is a literal string Assigning string literal to string reference E.g., string color = “blue”; Slide modified by L. Lilien
7
18.2 Fundamentals of Characters and Strings
Escape sequences and verbatim string syntax Equivalent expressions: string file = “C:\\MyFolder\\MySubolder\\MyFile.txt” - uses escape sequences string file uses verbatim string syntax Also allows strings to span multiple lines (preserves newlines, spaces, tabs) Slide modified by L. Lilien
8
READ LATER 18.2 Fundamentals of Characters and Strings (Cont.)
Performance Tip 18.1 If there are multiple occurrences of the same string literal object in an application, a single copy of it 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. To avoid excessive backslash characters, it is possible to exclude escape sequences and interpret all the characters in a string literally, using character. This approach also has the advantage of allowing strings to span multiple lines by preserving all newlines, spaces and tabs.
9
18.3 String Constructors Class String Provides eight constructors
For initialing strings in various ways 3 constructors shown in the following slides Slide modified by L. Lilien
10
Outline String Constructor.cs
Assign a string literal to string reference originalString. String Constructor.cs Copy a reference to another string literal. The string constructor can take a character array as an argument. The string constructor can take a char array and two int arguments for starting position and length. The string constructor can take as arguments a character and an int specifying the number of times to repeat that character in the string.
11
**READ LATER** 18.3 string Constructors (Cont.)
Assign a string literal to string reference originalString. Copy a reference to another string literal. The string constructor can take a character array as an argument. Software Engineering Observation 18.1 In most cases, it is not necessary to make a copy of an existing string (of class String). All strings (of class String) are immutable—their character contents cannot be changed after they are created.
12
**READ LATER** 18.3 string Constructors (Cont.)
The string constructor can take a char array and two int arguments for starting position and length. The string constructor can take as arguments a character and an int specifying the number of times to repeat that character in the string.
13
**READ ON YOUR OWN** 18.4 String Indexer, Length Property and CopyTo Method
Facilitates retrieval of any character in the string Similar to index in an array Length – a string property Returns the length of the string CopyTo - a string method Copies specified number of characters into a char array
14
** READ ON YOUR OWN** Outline The application in Fig. 18.2 presents the string indexer and the string property Length. StringMethods.cs (1 of 2 ) Property Length allows you to determine the number of characters in a string. Fig | string indexer, Length property and CopyTo method. (Part 1 of 2.)
15
** READ ON YOUR OWN** Outline
StringMethods.cs (2 of 2 ) The string indexer treats a string as an array of chars and returns each character at a specific position in the string. The string method CopyTo copies a specified number of characters from a string into a char array. Fig | string indexer, Length property and CopyTo method. (Part 2 of 2.)
16
Common Programming Error 18.1
** READ ON YOUR OWN** Outline Property Length allows you to determine the number of characters in a string. The string indexer treats a string as an array of chars and returns each character at a specific position in the string. As with arrays, the first element of a string is considered to be at position 0. StringCompare.cs (1 of 5 ) Common Programming Error 18.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. The string method CopyTo copies a specified number of characters from a string into a char array.
17
**READ ON YOUR OWN** 18.5 Comparing Strings
String comparisons Based on char representation by char codes (Unicode in C#) Greater than E.g., “Barb” > “Alice” Less than
18
**READ ON YOUR OWN** 18.5 Comparing Strings
Class String provides several ways to compare strings Method Equals and equality operator == Test objects for equality Use lexicographical comparison (Unicode values compared) Return a Boolean E.g., if string7 = “HELLO”: string7.Equals(“hello”); returns false string7 == “HELLO”; returns true Method CompareTo Test objects for equality and inequality (tells if < or >) Returns: -1 if invoking string < argument (string9 is invoking in example below) 0 if equal +1 invoking string > argument E.g., if string9 = “hello”: string9.CompareTo(“jello”); returns -1 (bec. “hello” is < “jello”)
19
Fig. 18.3 | string test to determine equality. (Part 1 of 4.)
**READ ON YOUR OWN** Outline When comparing two strings, C# simply compares the numeric codes of the characters in the strings. The application in Fig. 18.3 demonstrates the use of method Equals, method CompareTo and the equality operator (==). StringCompare.cs (1 of 3) Fig | string test to determine equality. (Part 1 of 4.)
20
Fig. 18.3 | string test to determine equality. (Part 2 of 4.)
**READ ON YOUR OWN** Outline StringCompare.cs (2 of 3 ) The string class’s Equals method uses a lexicographical comparison—comparing the integer Unicode values of character in each string. The overloaded string equality operator also uses a lexicographical comparison to compare two strings. static method Equals is used to compare the values of two strings, showing that string comparisons are case-sensetive. Fig | string test to determine equality. (Part 2 of 4.)
21
**READ ON YOUR OWN** Outline StringCompare.cs (3 of 3)
22
18.5 Comparing strings (Cont.)
**READ ON YOUR OWN** 18.5 Comparing strings (Cont.) Method Equals tests any two objects for equality (i.e., checks whether the objects contain identical contents). The string class’s Equals method uses a lexicographical comparison—comparing the integer Unicode values of character in each string. The overloaded string equality operator also uses a lexicographical comparison to compare two strings. static method Equals is used to compare the values of two strings, showing that string comparisons are case-sensitive.
23
18.5 Comparing strings (Cont.)
**READ ON YOUR OWN** 18.5 Comparing strings (Cont.) Method CompareTo returns: 0 if the strings are equal A negative value if the calling string is less than the argument string A positive value if the calling string is greater than the argument.
24
string.StartsWith( <string> )
**READ ON YOUR OWN** 18.5 Comparing Strings StartsWith string.StartsWith( <string> ) E.g. if string5 = “hello”: string5.StartsWith( “he” ); returns true EndsWith string.EndsWith( <string> ) string5.EndsWith( “glo” ); return false
25
Fig. 18.4 | StartsWith and EndsWith methods. (Part 1 of 2.)
**READ ON YOUR OWN** Outline Figure 18.4 shows how to test whether a string instance begins or ends with a given string. StringStart End.cs (1 of 2 ) Method StartsWith determines whether a string instance starts with the string text passed to it as an argument. Fig | StartsWith and EndsWith methods. (Part 1 of 2.)
26
Fig. 18.4 | StartsWith and EndsWith methods. (Part 2 of 2.)
READ ON YOUR OWN Outline StringStart End.cs (2 of 2 ) Method EndsWith determines whether a string instance ends with the string text passed to it as an argument. Fig | StartsWith and EndsWith methods. (Part 2 of 2.)
27
**SKIP**-- String Method GetHashCode
Often need to find needed info quickly E.g., Bob’s phone number in a big file Hash table – one of the best ways to do it Hash table Of class Object Make information easily/quickly accessible Storing object Takes object as input and calculates its hash code Hash code determines where (in which location) to store the object in hash table Finding object Hash code determines where in hash table to look for the object GetHashCode calculates hash code
28
**SKIP** StringHashCode.cs Define two strings
1 // Fig. 15.5: StringHashCode.cs 2 // Demonstrating method GetHashCode of class String. 3 4 using System; 5 using System.Windows.Forms; 6 7 // testing the GetHashCode method 8 class StringHashCode 9 { // The main entry point for the application. [STAThread] static void Main( string[] args ) { 14 string string1 = "hello"; string string2 = "Hello"; string output; 18 output = "The hash code for \"" + string1 + "\" is " + string1.GetHashCode() + "\n"; 21 output += "The hash code for \"" + string2 + "\" is " + string2.GetHashCode() + "\n"; 24 MessageBox.Show( output, "Demonstrating String " + "method GetHashCode", MessageBoxButtons.OK, MessageBoxIcon.Information ); 28 } // end method Main 30 31 } // end class StringHashCode StringHashCode.cs Define two strings Method GetHashCode is called to calculate for string1 and string2
29
**SKIP** Hash code value for strings “hello” and “Hello”
30
**READ ON YOUR OWN** 18.6 Locating Characters and Substrings in Strings
Search for a character or substring in a string E.g., find “efi” in ‘this is my definition” E.g., search for a word in a DOC report String methods doing this: IndexOf – 1st ocurrence of character/substring LastIndexOf IndexOfAny - last ocurrence of character/substring IndexOfAny - 1st ocurrence of character/substring LastIndexOfAny
31
** READ ON YOUR OWN** Outline The application in Fig. 18.5 demonstrates some versions of several string methods which search for a specified character or substring in a string. StringIndex Methods.cs (1 of 5 ) Method IndexOf locates the first occurrence of a character or substring in a string and returns its index, or -1 if it is not found. Fig | Searching for characters and substrings in strings. (Part 1 of 5.)
32
** READ ON YOUR OWN** Outline
StringIndex Methods.cs (2 of 5 ) Method LastIndexOf behaves like IndexOf, but searches from the end of the string. IndexOf and LastIndexOf can take a string instead of a character as the first argument. Fig | Searching for characters and substrings in strings. (Part 2 of 5.)
33
** READ ON YOUR OWN** Outline
StringIndex Methods.cs (3 of 5 ) IndexOf and LastIndexOf can take a string instead of a character as the first argument. Methods IndexOfAny and LastIndexOfAny take an array of characters as the first argument and return the index of the first occurrence of any of the characters in the array. Fig | Searching for characters and substrings in strings. (Part 3 of 5.)
34
** READ ON YOUR OWN** Outline
StringIndex Methods.cs (4 of 5 ) Methods IndexOfAny and LastIndexOfAny take an array of characters as the first argument and return the index of the first occurrence of any of the characters in the array. Fig | Searching for characters and substrings in strings. (Part 4 of 5.)
35
** READ ON YOUR OWN** Outline
StringIndex Methods.cs (5 of 5 ) Fig | Searching for characters and substrings in strings. (Part 5 of 5.)
36
18.6 Locating Characters and Substrings in strings
** READ ON YOUR OWN** 18.6 Locating Characters and Substrings in strings Method IndexOf locates the first occurrence of a character or substring in a string and returns its index, or -1 if it is not found. Method LastIndexOf behaves like IndexOf, but searches from the end of the string. IndexOf and LastIndexOf can take a string instead of a character as the first argument. Methods IndexOfAny and LastIndexOfAny take an array of characters as the first argument and return the index of the first occurrence of any of the characters in the array.
37
18.6 Locating Characters and Substrings in strings (Cont.)
** READ LATER ** 18.6 Locating Characters and Substrings in strings (Cont.) Common Programming Error 18.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.
38
**READ ON YOUR OWN** 18.7 Extracting Substrings from Strings
Substring methods Create a new string by copying a part of an existing string Methods return new string
39
Fig. 18.6 | Substrings generated from strings. (Part 1 of 2.)
** READ ON YOUR OWN** Outline Class string provides two Substring methods which create a new string by copying part of an existing string. The application in Fig. 18.6 demonstrates the use of both methods. SubString.cs (1 of 2 ) Fig | Substrings generated from strings. (Part 1 of 2.)
40
Fig. 18.6 | Substrings generated from strings. (Part 2 of 2.)
** READ ON YOUR OWN** Outline SubString.cs (2 of 2 ) The substring returned contains a copy of the characters from the specified starting index to the end of the string. The first argument specifies the starting index, and the second argument specifies the length of the substring to copy. Fig | Substrings generated from strings. (Part 2 of 2.) If the starting index is outside the string, or the supplied length of the substring is too large, an ArgumentOutOfRangeException is thrown.
41
**READ ON YOUR OWN** 18.8 Concatenating Strings
Static method Concat Takes two string and return a new string We have been using the + string operator for this Like the + operator, the static method Concat of class string (Fig. below) concatenates two strings and returns a new string.
42
** READ ON YOUR OWN** Outline SubConcatenation .cs
43
**READ ON YOUR OWN** 18.9 Miscellaneous String Methods
Method Replace Original string remains unchanged Original string returned if no match Method ToUpper Replace lower case letter Method ToLower
44
18.9 Miscellaneous String Methods
** READ ON YOUR OWN** 18.9 Miscellaneous String Methods Method ToString Obtain a string representation of any object We know it very well! Method Trim Remove whitespaces Remove all characters that are in the array given as the argument
45
** READ ON YOUR OWN** Outline The application in Fig. 18.8 demonstrates the use of several more string methods that return modified copies of a string. StringMethods2 .cs (1 of 4 ) Fig | string methods Replace, ToLower, ToUpper and Trim. (Part 1 of 3.)
46
** READ ON YOUR OWN** Outline
StringMethods2 .cs (2 of 4 ) Method Replace returns a new string, replacing every occurrence of its first argument with its second argument. string method ToUpper generates a new string that replaces any lowercase letters with their uppercase equivalents. Use string method Trim to remove all whitespace characters that appear at the beginning and end of a string. Method ToLower converts a string to lowercase. Fig | string methods Replace, ToLower, ToUpper and Trim. (Part 2 of 3.)
47
** READ ON YOUR OWN** Outline
StringMethods2 .cs (3 of 4 ) Fig | string methods Replace, ToLower, ToUpper and Trim. (Part 3 of 3.)
48
Method ToLower converts a string to lowercase.
** READ ON YOUR OWN** Outline Method Replace returns a new string, replacing every occurrence of its first argument with its second argument. string method ToUpper generates a new string that replaces any lowercase letters with their uppercase equivalents. Method ToLower converts a string to lowercase. Use string method Trim to remove all whitespace characters that appear at the beginning and end of a string. Trim can also take a character array and return a copy of the string that does not begin or end with the characters in the array argument. StringMethods2 .cs (4 of 4 )
49
18.10 Class StringBuilder Mutable strings
So far – string processing methods for object class String Strings were immutable The methods did not change original strings Returned new strings rather than changing old ones Now other class: StringBuilder To create and manipulate dynamic strings Mutable strings Capable of dynamic resizing Exceeding capacity of StringBuilder causes the string capacity to increase
50
18.10 Class StringBuilder – cont.
** READ LATER ** 18.10 Class StringBuilder – cont. Objects of class string are immutable. Class StringBuilder is used to create and manipulate dynamic string information—i.e., mutable strings. StringBuilder is much more efficient for working with large numbers of strings than creating individual immutable strings Performance Tip 18.2 Objects of class string are immutable (i.e., constant strings), whereas objects of class StringBuilder are mutable. Thanks to immutablity of strings, C# can perform certain optimizations involving strings, because it knows these objects will not change. - E.g., optimizations such as the sharing of one string among multiple references
51
18.10 Class StringBuilder – cont.
** READ LATER ** 18.10 Class StringBuilder – cont. We do not discuss the StringBuilder class any more Optional information follows “The End”
52
18.14 Char Methods Structure
Similar to a class but not a class Includes methods and properties - like classes Same member access operator ‘.’ as a class Can use only some modifiers used by classes: public, private - Can’t use protected or protected internal Implicitly sealed – unlike classes (classes must be explicitly sealed, which prevents overriding them) Structures derived from class ValueType (ValueType is a child of class object) Created with keyword struct Many primitive data types are actually aliases for different structures E.g., int is defined by struct System.Int32 long is defined by struct System.Int64 char is defined by struct System.Char In other words, char is an alias for the struct Char
53
Char is a structure: struct Char
18.14 Char Methods Char is a structure: struct Char A structure for characters Methods: Most are static Most take 1 argument Selected Char methods: IsLower IsUpper ToUpper ToLower IsPunctuation IsSymbol IsWhiteSpace
54
18.14 Char Methods (Cont.) All struct types are implicitly sealed
** READ LATER ** 18.14 Char Methods (Cont.) All struct types are implicitly sealed No virtual or abstract methods Members cannot be declared protected or protected internal.
55
Testing Methods For chars Outline
GUI for Next Program – Testing Methods For chars Outline (a) (b) (c) StaticCharMethods .cs (4 of 4 ) (d) (e)
56
Figure 18.15 demonstrates some static methods of the Char struct.
Outline Figure 18.15 demonstrates some static methods of the Char struct. StaticCharMethods .cs (1 of 4 ) Fig | Char’s static character-testing and case-conversion methods. (Part 1 of 4.)
57
Outline StaticCharMethods .cs (2 of 4 ) Char method IsDigit determines whether a character is defined as a digit. IsLetter determines whether a character is a letter. IsLetterOrDigit determines whether a character is a letter or a digit. IsLower determines whether a character is a lowercase letter. IsUpper determines whether a character is an uppercase letter. ToUpper returns a character’s uppercase equivalent, or the original argument if there is no uppercase equivalent. Fig | Char’s static character-testing and case-conversion methods. (Part 2 of 4.)
58
Outline StaticCharMethods .cs (3 of 4 ) ToLower returns a character lowercase equivalent, or the original argument if there is no lowercase equivalent. IsPunctuation determines whether a character is a punctuation mark, such as "!", ":" or ")". IsSymbol determines whether a character is a symbol, such as "+", "=" or "^". Fig | Char’s static character-testing and case-conversion methods. (Part 3 of 4.)
59
Outline (a) (b) (c) StaticCharMethods .cs (4 of 4 ) (d) (e) Fig | Char’s static character-testing and case-conversion methods. (Part 4 of 4.)
60
** READ LATER ** 18.14 Char Methods (Cont.) Char method IsDigit determines whether a character is defined as a digit. IsLetter determines whether a character is a letter. IsLetterOrDigit determines whether a character is a letter or a digit. IsLower determines whether a character is a lowercase letter. IsUpper determines whether a character is an uppercase letter. ToUpper returns a character’s uppercase equivalent, or the original argument if there is no uppercase equivalent.
61
** READ LATER ** 18.14 Char Methods (Cont.) ToLower returns a character lowercase equivalent, or the original argument if there is no lowercase equivalent. IsPunctuation determines whether a character is a punctuation mark, such as "!", ":" or ")". IsSymbol determines whether a character is a symbol, such as "+", "=" or "^". Structure type Char contains more static methods similar to those shown in this example, such as IsWhiteSpace. The struct also contains several public instance methods, many of which we have seen before in other classes, such as ToString, Equals, and CompareTo.
62
The End of Ch. 18 (ed.3)
63
Optional material follows
– optional self-study
64
18.10 Class StringBuilder Mutable strings
** OBLIGATORY SLIDE REPEATED FOR COMPLETENESS** 18.10 Class StringBuilder So far – string processing methods for object class String Strings were immutable The methods did not change original strings Returned new strings rather than changing old ones Now other class: StringBuilder To create and manipulate dynamic strings Mutable strings Capable of dynamic resizing Exceeding capacity of StringBuilder causes the string capacity to increase
65
18.10 Class StringBuilder Performance Tip 18.2
* OBLIGATORY “READ LATER” SLIDE REPEATED FOR COMPLETENESS * 18.10 Class StringBuilder Objects of class string are immutable. Class StringBuilder is used to create and manipulate dynamic string information—i.e., mutable strings. StringBuilder is much more efficient for working with large numbers of strings than creating individual immutable strings Performance Tip 18.2 Objects of class string are immutable (i.e., constant strings), whereas objects of class StringBuilder are mutable. Thanks to immutablity of strings, C# can perform certain optimizations involving strings, because it knows these objects will not change. - E.g., optimizations such as the sharing of one string among multiple references
66
** SKIP ** 18.10 Class StringBuilder
Class StringBuilder has 6 constructors 3 shown below
67
** SKIP ** Outline Class StringBuilderConstructor (Fig. 18.9) demonstrates three of StringBuilder’s six overloaded constructors. StringBuilder Constructor.cs (1 of 2) The no-parameter StringBuilder constructor creates an empty StringBuilder with a default capacity of 16 characters. Given a single int argument, the StringBuilder constructor creates an empty StringBuilder that has the initial capacity specified in the int argument. Given a single string argument, the StringBuilder constructor creates a StringBuilder containing the characters of the string argument.
68
** SKIP ** Outline The no-parameter StringBuilder constructor creates an empty StringBuilder with a default capacity of 16 characters. Given a single int argument, the StringBuilder constructor creates an empty StringBuilder that has the initial capacity specified in the int argument. Given a single string argument, the StringBuilder constructor creates a StringBuilder containing the characters of the string argument. Its initial capacity is the smallest power of two greater than or equal to the number of characters in the argument string, with a minimum of 16. StringBuilder Constructor.cs (2 of 2)
69
** SKIP ** Length and Capacity Properties, EnsureCapacity Method and Indexer of Class StringBuilder Method EnsureCapacity Allows programmers to guarantee StringBuilder has a certain capacity Reduces the number of times capacity must be increased EnsureCapacity approximately doubles the current capacity of a StringBuilder instance Details: p. 781 Examples of capacity provided by instantiation of the StringBuilder class: For explicitly demanded initial capacity, it is as demanded (cf. line 19 in Slide 40 ) For empty string argument : default initial capacity is 16 (cf. line 18 in Slide 40) For non-empty string argument , default initial capacity is the s\mallest power of 2 larger than string length (cf. line 20 in Slide 40) Properties of StringBuilder Length property returns number of characters currently in StringBuilder Capacity property returns capacity i.e., the number of characters that StringBuilder can store without allocating memory
70
Fig. 18.10 | StringBuilder size manipulation. (Part 1 of 3.)
** SKIP ** Outline Class StringBuilder provides the Length and Capacity properties. Method EnsureCapacity doubles the StringBuilder instance’s current capacity. If this doubled value is greater than the value that the programmer wishes to ensure, that value becomes the new capacity. Otherwise, EnsureCapacity alters the capacity to make it equal to the requested number. The program in Fig. 18.10 demonstrates the use of these methods and properties. StringBuilderFea tures.cs (1 of 3 ) Fig | StringBuilder size manipulation. (Part 1 of 3.)
71
Fig. 18.10 | StringBuilder size manipulation. (Part 2 of 3.)
** SKIP ** Outline StringBuilderFea tures.cs (2 of 3 ) Expand the capacity of the StringBuilder to a minimum of 75 characters. Fig | StringBuilder size manipulation. (Part 2 of 3.)
72
Fig. 18.10 | StringBuilder size manipulation. (Part 3 of 3.)
** SKIP ** Outline StringBuilderFea tures.cs (3 of 3 ) Use property Length to set the length of the StringBuilder to 10. Fig | StringBuilder size manipulation. (Part 3 of 3.)
73
** SKIP ** 18.11 Length and Capacity Properties, EnsureCapacity Method and Indexer of Class StringBuilder (Cont.) When a StringBuilder exceeds its capacity, it grows in the same manner as if method EnsureCapacity had been called. If Length is set to a value less than the number of characters in the StringBuilder, the contents of the StringBuilder are truncated. Common Programming Error 18.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 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). The string.Empty should be used if you need a string with no characters.
74
** SKIP ** 18.12 Append and AppendFormat Methods of Class StringBuilder
Append method Allows various data-type values to be appended to the end of a StringBuilder object instance Converts its argument into string AppendFormat method Like Append + converts string to a specifiable format
75
Fig. 18.11 | Append methods of StringBuilder. (Part 1 of 3.)
** SKIP ** Outline Class StringBuilder provides 19 overloaded Append methods that allow various types of values to be added to the end of a StringBuilder. The Framework Class Library provides versions for each of the simple types and for character arrays, strings and objects. Figure 18.11 demonstrates the use of several Append methods. StringBuilder Append.cs (1 of 3 ) Fig | Append methods of StringBuilder. (Part 1 of 3.)
76
Fig. 18.11 | Append methods of StringBuilder. (Part 2 of 3.)
** SKIP ** Outline StringBuilder Append.cs (2 of 3 ) Use 10 different overloaded Append methods to attach the string representations of various types to the end of the StringBuilder. Fig | Append methods of StringBuilder. (Part 2 of 3.)
77
Fig. 18.11 | Append methods of StringBuilder. (Part 3 of 3.)
** SKIP ** Outline StringBuilder Append.cs (3 of 3 ) Use 10 different overloaded Append methods to attach the string representations of various types to the end of the StringBuilder. Fig | Append methods of StringBuilder. (Part 3 of 3.)
78
Fig. 18.12 | StringBuilder’s AppendFormat method. (Part 1 of 2.)
** SKIP ** Outline Class StringBuilder’s method AppendFormat converts a string to a specified format, then appends it to the StringBuilder. The example in Fig. 18.12 demonstrates the use of AppendFormat. StringBuilder AppendFormat.cs (1 of 2 ) The numbers in curly braces specify an index to objectArray, passed as the second argument to appendFormat. Fig | StringBuilder’s AppendFormat method. (Part 1 of 2.)
79
Fig. 18.12 | StringBuilder’s AppendFormat method. (Part 2 of 2.)
** SKIP ** Outline StringBuilder AppendFormat.cs (2 of 2 ) {0:d3} specifies that the first argument will be formatted as a three-digit decimal (with leading zeros, if necessary). {0, 4} specifies that the formatted string should have four characters and be right aligned. {0: -4} specifies that the strings should be aligned to the left. Fig | StringBuilder’s AppendFormat method. (Part 2 of 2.)
80
18.12 Append and AppendFormat Methods of Class StringBuilder (Cont.)
** SKIP ** 18.12 Append and AppendFormat Methods of Class StringBuilder (Cont.) Formats have the form {X[,Y][:FormatString]}. X is the number of the argument to be formatted, counting from zero. Y is an optional argument, which can be positive or negative, indicating how many characters should be in the result. A positive integer aligns the string to the right; a negative integer aligns it to the left. The optional FormatString applies a particular format to the argument—currency, decimal or scientific, among others. One version of AppendFormat takes a string specifying the format and an array of objects to serve as the arguments to the format string. AppendFormat can take a string containing a format and an object to which the format is applied.
81
18.12 Append and AppendFormat Methods of Class StringBuilder (Cont.)
** SKIP ** 18.12 Append and AppendFormat Methods of Class StringBuilder (Cont.) Class StringBuilder provides 18 overloaded Insert methods to allow various types of data to be inserted at any position in a StringBuilder. Each method inserts its second argument into the StringBuilder in front of the character in the position specified by the first argument. Class StringBuilder also provides method Remove for deleting any portion of a StringBuilder. Method Remove takes two arguments—the index at which to begin deletion and the number of characters to delete.
82
** SKIP ** 18.13 Insert, Remove and Replace Methods of Class StringBuilder
Insert method StringBuilder provides 18 overloaded methods Insert at any position Program may throw ArgumentOutOfRangeException Remove method Takes two arguments buffer.Remove(x, y) starting from position x of ‘buffer’ remove y chars Replace method Substitute specified string
83
Fig. 18.13 | StringBuilder text insertion and removal. (Part 1 of 3.)
** SKIP ** Outline The Insert and Remove methods are demonstrated in Fig. 18.13. StringBuilder InsertRemove.cs (1 of 3 ) Fig | StringBuilder text insertion and removal. (Part 1 of 3.)
84
Fig. 18.13 | StringBuilder text insertion and removal. (Part 2 of 3.)
** SKIP ** Outline StringBuilder InsertRemove.cs (2 of 3 ) Fig | StringBuilder text insertion and removal. (Part 2 of 3.)
85
Fig. 18.13 | StringBuilder text insertion and removal. (Part 3 of 3.)
** SKIP ** Outline StringBuilder InsertRemove.cs (3 of 3 ) Fig | StringBuilder text insertion and removal. (Part 3 of 3.)
86
Fig. 18.14 | StringBuilder text replacement. (Part 1 of 2.)
** SKIP ** Outline Replace searches for a specified string or character and substitutes another string or character in its place. Figure 18.14 demonstrates this method. StringBuilder Replace.cs (1 of 2 ) Fig | StringBuilder text replacement. (Part 1 of 2.)
87
Fig. 18.14 | StringBuilder text replacement. (Part 2 of 2.)
** SKIP ** Outline StringBuilder Replace.cs (2 of 2 ) This overload of Replace replaces all instances of the first character with the second character, beginning at the index specified by the first int and continuing for a count specified by the second int. Fig | StringBuilder text replacement. (Part 2 of 2.) Another overload of this method takes two characters as parameters and replaces each occurrence of the first character with the second character.
88
SKIP. >> SELF-STUDY << 18
** SKIP** >> SELF-STUDY << Card Shuffling and Dealing Simulation IMPORTANT: Get a taste of running computer simulations! Theoretical study and experimental study used to be the only two major research paradigms in human history Simulation study is a new, third major research paradigm (enabled by computers) Class Card Two string instance variable Face and suit Method ToString
89
Fig. 18.16 | Card class. (Part 1 of 2.)
** SKIP ** Outline Class Card (Fig. 18.16) contains two string instance variables—face and suit—that store references to the face value and suit name of a specific card. Card.cs (1 of 2 ) The constructor for the class receives two strings that it uses to initialize face and suit. Fig | Card class. (Part 1 of 2.)
90
Fig. 18.16 | Card class. (Part 2 of 2.)
** SKIP ** Outline Card.cs (2 of 2 ) Method ToString (lines 18–21) creates a string consisting of the card’s face and suit to identify the card when it is dealt. Fig | Card class. (Part 2 of 2.)
91
Fig. 18.17 | Card shuffling and dealing simulation. (Part 1 of 6.)
** SKIP ** Outline We develop the DeckForm application (Fig. 18.17), which creates a deck of 52 playing cards, using Card objects. DeckForm.cs (1 of 6 ) Fig | Card shuffling and dealing simulation. (Part 1 of 6.)
92
Fig. 18.17 | Card shuffling and dealing simulation. (Part 2 of 6.)
** SKIP ** Outline DeckForm.cs (2 of 6 ) Each Card is instantiated and initialized with two strings—one from the faces array and one from the suits array. Fig | Card shuffling and dealing simulation. (Part 2 of 6.)
93
Fig. 18.17 | Card shuffling and dealing simulation. (Part 3 of 6.)
** SKIP ** Outline DeckForm.cs (3 of 6 ) Fig | Card shuffling and dealing simulation. (Part 3 of 6.)
94
Fig. 18.17 | Card shuffling and dealing simulation. (Part 4 of 6.)
** SKIP ** Outline DeckForm.cs (4 of 6 ) Swap each card with another randomly chosen card. Fig | Card shuffling and dealing simulation. (Part 4 of 6.)
95
Fig. 18.17 | Card shuffling and dealing simulation. (Part 5 of 6.)
** SKIP ** Outline DeckForm.cs (5 of 6 ) If the deck is not empty, return a Card object reference; otherwise, it returns null. Fig | Card shuffling and dealing simulation. (Part 5 of 6.)
96
Fig. 18.17 | Card shuffling and dealing simulation. (Part 6 of 6.)
** SKIP ** Outline DeckForm.cs (6 of 6 ) (a) (b) (c) (c) (d) Fig | Card shuffling and dealing simulation. (Part 6 of 6.)
97
18.16 Introduction to Regular-Expression Processing
** SKIP ** 18.16 Introduction to Regular-Expression Processing Regular expressions are Specially formatted strings used to find patterns in text Facilitate string search E.g., very useful in compilers Used to validate the syntax of a program
98
Example: Simple Regular Expressions
** SKIP ** Example: Simple Regular Expressions Few more patterns: . – (a dot) matches any single character * – matches zero or more repetitions of the preceding pattern (see below) [x-y] – matches range from x to y (inclusive) —[k-m] matches: k or l or m - e.g. —[k-mp-s] matches: k or l or m OR p or q or r or s Example regular expression: Jo.*\sin\s20\d[0-6]. Matches a substring: Starting with ‘Jo’ Followed by any number of any characters Followed by a whitespace Followed by ‘in’ Followed by a whitespace Followed by ‘20’ Followed by any digit Followed by a digit between 0 and 6 (inclusive) Followed by ‘.’ E.g., - matches “John was here in 2005.” or “Joan will repay in 2090.” - does not match ‘Joan will repay in 2098.” (why does not match?)
99
18.16 Introduction to Regular-Expression Processing
** SKIP ** 18.16 Introduction to Regular-Expression Processing SKIP the rest of Section 18.16
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.