Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2009 Pearson Education, Inc. All rights reserved. 1 Ch.18 Strings, Characters [and Regular Expressions] Many slides modified by Prof. L. Lilien (even.

Similar presentations


Presentation on theme: " 2009 Pearson Education, Inc. All rights reserved. 1 Ch.18 Strings, Characters [and Regular Expressions] Many slides modified by Prof. L. Lilien (even."— Presentation transcript:

1  2009 Pearson Education, Inc. All rights reserved. 1 Ch.18 Strings, Characters [and Regular Expressions] Many slides modified by Prof. L. Lilien (even many without explicit message). Slides added by L.Lilien are © 2006-2010 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., emailed) request.

2  2009 Pearson Education, Inc. All rights reserved. 2 Outline (ed.3) 18.1 Introduction 18.2 Fundamentals of Characters and String s 18.3 String Constructors ------ READ ON YOUR OWN – 18.4-18.10-- -----  18.4 String Indexer, Length Property and CopyTo Method 18.5 Comparing String s String Method GetHashCode 18.6 Locating Characters and Substrings in String s 18.7 Extracting Substrings from String s 18.8 Concatenating String s 18.9 Miscellaneous String Methods <------ END of READ ON YOUR OWN 18.4-18.10-- ------ 18.10 (a part) Class StringBuilder ( just signaled: how different, why needed) ------ SKIP most of 18.10, 18.11-18.13 ------ > 18.11 Length and Capacity Properties, EnsureCapacity Method and Indexer of Class StringBuilder 18.12 Append and AppendFormat Methods of Class StringBuilder 18.13 Insert, Remove and Replace Methods of Class StringBuilder 18.14 Char Methods ------ SKIP 18.15-18.16 ------ > 18.15 >> SELF-STUDY<< Card Shuffling and Dealing Simulation 18.16 Regular Expressions and Class Regex 18.16.1 Regular Expression Example 18.16.2 Validating User Input with Regular Expressions 18.16.3 Regex methods Replace and Split

3  2009 Pearson Education, Inc. All rights reserved. 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  2009 Pearson Education, Inc. All rights reserved. 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 … 0 1 2 3 … ! @ # …) 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  2009 Pearson Education, Inc. All rights reserved. 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  2009 Pearson Education, Inc. All rights reserved. 6 18.2 Fundamentals of Characters and Strings String – 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  2009 Pearson Education, Inc. All rights reserved. 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 = @“C:\MyFolder\MySubolder\MyFile.txt” -uses verbatim string syntax -Also allows strings to span multiple lines (preserves newlines, spaces, tabs) Slide modified by L. Lilien

8  2009 Pearson Education, Inc. All rights reserved. 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 the @ character. – This approach also has the advantage of allowing strings to span multiple lines by preserving all newlines, spaces and tabs.

9  2009 Pearson Education, Inc. All rights reserved. 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  2009 Pearson Education, Inc. All rights reserved. 10 Outline String Constructor.cs Assign a string literal to string reference originalString. The string constructor can take a char array and two int arguments for starting position and length. Copy a reference to another string literal. The string constructor can take a character array as an argument. 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  2009 Pearson Education, Inc. All rights reserved. 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  2009 Pearson Education, Inc. All rights reserved. 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  2009 Pearson Education, Inc. All rights reserved. 13 READ ON YOUR OWN 18.4 String Indexer, Length Property and CopyTo Method String indexer – 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  2009 Pearson Education, Inc. All rights reserved. 14 The application in Fig. 18.2 presents the string indexer and the string property Length. Fig. 18.2 | string indexer, Length property and CopyTo method. (Part 1 of 2.) Outline StringMethods.cs (1 of 2 ) Property Length allows you to determine the number of characters in a string. ** READ ON YOUR OWN**

15  2009 Pearson Education, Inc. All rights reserved. 15 Fig. 18.2 | string indexer, Length property and CopyTo method. (Part 2 of 2.) Outline StringMethods.cs (2 of 2 ) The string indexer treats a string as an array of char s 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. ** READ ON YOUR OWN**

16  2009 Pearson Education, Inc. All rights reserved. 16 Property Length allows you to determine the number of characters in a string. The string indexer treats a string as an array of char s 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. Outline 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. ** READ ON YOUR OWN**

17  2009 Pearson Education, Inc. All rights reserved. 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  2009 Pearson Education, Inc. All rights reserved. 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 ) Use lexicographical comparison (Unicode values compared) - 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  2009 Pearson Education, Inc. All rights reserved. 19 When comparing two string s, C# simply compares the numeric codes of the characters in the string s. The application in Fig. 18.3 demonstrates the use of method Equals, method CompareTo and the equality operator ( == ). Outline StringCompare.cs (1 of 3) Fig. 18.3 | string test to determine equality. (Part 1 of 4.) READ ON YOUR OWN

20  2009 Pearson Education, Inc. All rights reserved. 20 Fig. 18.3 | string test to determine equality. (Part 2 of 4.) 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 string s. static method Equals is used to compare the values of two string s, showing that string comparisons are case- sensetive. READ ON YOUR OWN

21  2009 Pearson Education, Inc. All rights reserved. 21 Outline StringCompare.cs (3 of 3) READ ON YOUR OWN

22  2009 Pearson Education, Inc. All rights reserved. 22 18.5 Comparing string s (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 string s. static method Equals is used to compare the values of two string s, showing that string comparisons are case-sensitive. READ ON YOUR OWN

23  2009 Pearson Education, Inc. All rights reserved. 23 18.5 Comparing string s (Cont.) Method CompareTo returns: – 0 if the string s 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. READ ON YOUR OWN

24  2009 Pearson Education, Inc. All rights reserved. 24 18.5 Comparing Strings StartsWith – string.StartsWith( ) - E.g. if string5 = “hello”: string5.StartsWith( “he” ); returns true EndsWith – string.EndsWith( ) - E.g. if string5 = “hello”: string5.EndsWith( “glo” ); return false READ ON YOUR OWN

25  2009 Pearson Education, Inc. All rights reserved. 25 Figure 18.4 shows how to test whether a string instance begins or ends with a given string. Fig. 18.4 | StartsWith and EndsWith methods. (Part 1 of 2.) Outline StringStart End.cs (1 of 2 ) Method StartsWith determines whether a string instance starts with the string text passed to it as an argument. READ ON YOUR OWN

26  2009 Pearson Education, Inc. All rights reserved. 26 Fig. 18.4 | StartsWith and EndsWith methods. (Part 2 of 2.) 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. READ ON YOUR OWN

27  2009 Pearson Education, Inc. All rights reserved. 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 – Takes object as input and calculates its hash code – Hash code determines where in hash table to look for the object GetHashCode calculates hash code

28  2009 Pearson Education, Inc. All rights reserved. 28 StringHashCo de.cs 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 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string[] args ) 13 { 14 15 string string1 = "hello"; 16 string string2 = "Hello"; 17 string output; 18 19 output = "The hash code for \"" + string1 + 20 "\" is " + string1.GetHashCode() + "\n"; 21 22 output += "The hash code for \"" + string2 + 23 "\" is " + string2.GetHashCode() + "\n"; 24 25 MessageBox.Show( output, "Demonstrating String " + 26 "method GetHashCode", MessageBoxButtons.OK, 27 MessageBoxIcon.Information ); 28 29 } // end method Main 30 31 } // end class StringHashCode Define two strings **SKIP** Method GetHashCode is called to calculate for string1 and string2

29  2009 Pearson Education, Inc. All rights reserved. 29 Hash code value for strings “hello” and “Hello” **SKIP**

30  2009 Pearson Education, Inc. All rights reserved. 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 – 1 st ocurrence of character/substring – LastIndexOf IndexOfAny - last ocurrence of character/substring – IndexOfAny - 1 st ocurrence of character/substring – LastIndexOfAny

31  2009 Pearson Education, Inc. All rights reserved. 31 The application in Fig. 18.5 demonstrates some versions of several string methods which search for a specified character or substring in a string. Fig. 18.5 | Searching for characters and substrings in string s. (Part 1 of 5.) Outline 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. ** READ ON YOUR OWN**

32  2009 Pearson Education, Inc. All rights reserved. 32 Outline StringIndex Methods.cs (2 of 5 ) Fig. 18.5 | Searching for characters and substrings in string s. (Part 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. ** READ ON YOUR OWN**

33  2009 Pearson Education, Inc. All rights reserved. 33 Outline StringIndex Methods.cs (3 of 5 ) Fig. 18.5 | Searching for characters and substrings in string s. (Part 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. ** READ ON YOUR OWN**

34  2009 Pearson Education, Inc. All rights reserved. 34 Outline StringIndex Methods.cs (4 of 5 ) Fig. 18.5 | Searching for characters and substrings in string s. (Part 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. ** READ ON YOUR OWN**

35  2009 Pearson Education, Inc. All rights reserved. 35 Outline StringIndex Methods.cs (5 of 5 ) Fig. 18.5 | Searching for characters and substrings in string s. (Part 5 of 5.) ** READ ON YOUR OWN**

36  2009 Pearson Education, Inc. All rights reserved. 36 18.6 Locating Characters and Substrings in string s 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. ** READ ON YOUR OWN**

37  2009 Pearson Education, Inc. All rights reserved. 37 18.6 Locating Characters and Substrings in string s (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. ** READ LATER **

38  2009 Pearson Education, Inc. All rights reserved. 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  2009 Pearson Education, Inc. All rights reserved. 39 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. Fig. 18.6 | Substrings generated from string s. (Part 1 of 2.) Outline SubString.cs (1 of 2 ) ** READ ON YOUR OWN**

40  2009 Pearson Education, Inc. All rights reserved. 40 Fig. 18.6 | Substrings generated from string s. (Part 2 of 2.) 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. If the starting index is outside the string, or the supplied length of the substring is too large, an ArgumentOutOfRangeException is thrown. ** READ ON YOUR OWN**

41  2009 Pearson Education, Inc. All rights reserved. 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. 18.7 - below) concatenates two string s and returns a new string.

42  2009 Pearson Education, Inc. All rights reserved. 42 Outline SubConcatenation.cs ** READ ON YOUR OWN**

43  2009 Pearson Education, Inc. All rights reserved. 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 – Original string remains unchanged – Original string returned if no match Method ToLower – Replace lower case letter – Original string remains unchanged – Original string returned if no match

44  2009 Pearson Education, Inc. All rights reserved. 44 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 ** READ ON YOUR OWN**

45  2009 Pearson Education, Inc. All rights reserved. 45 The application in Fig. 18.8 demonstrates the use of several more string methods that return modified copies of a string. Outline StringMethods2.cs (1 of 4 ) Fig. 18.8 | string methods Replace, ToLower, ToUpper and Trim. (Part 1 of 3.) ** READ ON YOUR OWN**

46  2009 Pearson Education, Inc. All rights reserved. 46 Outline StringMethods2.cs (2 of 4 ) Fig. 18.8 | string methods Replace, ToLower, ToUpper and Trim. (Part 2 of 3.) 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. ** READ ON YOUR OWN**

47  2009 Pearson Education, Inc. All rights reserved. 47 Outline StringMethods2.cs (3 of 4 ) Fig. 18.8 | string methods Replace, ToLower, ToUpper and Trim. (Part 3 of 3.) ** READ ON YOUR OWN**

48  2009 Pearson Education, Inc. All rights reserved. 48 Outline StringMethods2.cs (4 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. 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. ** READ ON YOUR OWN**

49  2009 Pearson Education, Inc. All rights reserved. 49 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

50  2009 Pearson Education, Inc. All rights reserved. 50 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 string s 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 string s, C# can perform certain optimizations involving string s, because it knows these objects will not change. - E.g., optimizations such as the sharing of one string among multiple references ** READ LATER **

51  2009 Pearson Education, Inc. All rights reserved. 51 ** SKIP ** 18.10 Class StringBuilder Class StringBuilder has 6 constructors – 3 shown below

52  2009 Pearson Education, Inc. All rights reserved. 52 Class StringBuilderConstructor (Fig. 18.9) demonstrates three of StringBuilder ’s six overloaded constructors. Outline 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. ** SKIP **

53  2009 Pearson Education, Inc. All rights reserved. 53 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) ** SKIP **

54  2009 Pearson Education, Inc. All rights reserved. 54 ** SKIP ** 18.11 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

55  2009 Pearson Education, Inc. All rights reserved. 55 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. Outline StringBuilderFea tures.cs (1 of 3 ) Fig. 18.10 | StringBuilder size manipulation. (Part 1 of 3.) ** SKIP **

56  2009 Pearson Education, Inc. All rights reserved. 56 Outline StringBuilderFea tures.cs (2 of 3 ) Fig. 18.10 | StringBuilder size manipulation. (Part 2 of 3.) Expand the capacity of the StringBuilder to a minimum of 75 characters. ** SKIP **

57  2009 Pearson Education, Inc. All rights reserved. 57 Outline StringBuilderFea tures.cs (3 of 3 ) Fig. 18.10 | StringBuilder size manipulation. (Part 3 of 3.) Use property Length to set the length of the StringBuilder to 10. ** SKIP **

58  2009 Pearson Education, Inc. All rights reserved. 58 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. ** SKIP **

59  2009 Pearson Education, Inc. All rights reserved. 59 ** 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

60  2009 Pearson Education, Inc. All rights reserved. 60 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, string s and object s. Figure 18.11 demonstrates the use of several Append methods. Outline StringBuilder Append.cs (1 of 3 ) Fig. 18.11 | Append methods of StringBuilder. (Part 1 of 3.) ** SKIP **

61  2009 Pearson Education, Inc. All rights reserved. 61 Outline StringBuilder Append.cs (2 of 3 ) Fig. 18.11 | Append methods of StringBuilder. (Part 2 of 3.) Use 10 different overloaded Append methods to attach the string representations of various types to the end of the StringBuilder. ** SKIP **

62  2009 Pearson Education, Inc. All rights reserved. 62 Outline StringBuilder Append.cs (3 of 3 ) Fig. 18.11 | Append methods of StringBuilder. (Part 3 of 3.) Use 10 different overloaded Append methods to attach the string representations of various types to the end of the StringBuilder. ** SKIP **

63  2009 Pearson Education, Inc. All rights reserved. 63 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. Fig. 18.12 | StringBuilder ’s AppendFormat method. (Part 1 of 2.) Outline StringBuilder AppendFormat.cs (1 of 2 ) The numbers in curly braces specify an index to objectArray, passed as the second argument to appendFormat. ** SKIP **

64  2009 Pearson Education, Inc. All rights reserved. 64 Fig. 18.12 | StringBuilder ’s AppendFormat method. (Part 2 of 2.) 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. ** SKIP **

65  2009 Pearson Education, Inc. All rights reserved. 65 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. ** SKIP **

66  2009 Pearson Education, Inc. All rights reserved. 66 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. 18.12 Append and AppendFormat Methods of Class StringBuilder (Cont.) ** SKIP **

67  2009 Pearson Education, Inc. All rights reserved. 67 ** 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 – Program may throw ArgumentOutOfRangeException Replace method – Substitute specified string

68  2009 Pearson Education, Inc. All rights reserved. 68 The Insert and Remove methods are demonstrated in Fig. 18.13. Fig. 18.13 | StringBuilder text insertion and removal. (Part 1 of 3.) Outline StringBuilder InsertRemove.cs (1 of 3 ) ** SKIP **

69  2009 Pearson Education, Inc. All rights reserved. 69 Fig. 18.13 | StringBuilder text insertion and removal. (Part 2 of 3.) Outline StringBuilder InsertRemove.cs (2 of 3 ) ** SKIP **

70  2009 Pearson Education, Inc. All rights reserved. 70 Fig. 18.13 | StringBuilder text insertion and removal. (Part 3 of 3.) Outline StringBuilder InsertRemove.cs (3 of 3 ) ** SKIP **

71  2009 Pearson Education, Inc. All rights reserved. 71 Outline StringBuilder Replace.cs (1 of 2 ) Fig. 18.14 | StringBuilder text replacement. (Part 1 of 2.) Replace searches for a specified string or character and substitutes another string or character in its place. Figure 18.14 demonstrates this method. ** SKIP **

72  2009 Pearson Education, Inc. All rights reserved. 72 Outline StringBuilder Replace.cs (2 of 2 ) Fig. 18.14 | StringBuilder text replacement. (Part 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. Another overload of this method takes two characters as parameters and replaces each occurrence of the first character with the second character. ** SKIP **

73  2009 Pearson Education, Inc. All rights reserved. 73 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 – 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

74  2009 Pearson Education, Inc. All rights reserved. 74 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

75  2009 Pearson Education, Inc. All rights reserved. 75 18.14 Char Methods (Cont.) All struct types are implicitly sealed – No virtual or abstract methods – Members cannot be declared protected or protected internal. ** READ LATER **

76  2009 Pearson Education, Inc. All rights reserved. 76 Outline StaticCharMethods.cs (4 of 4 ) (a ) (b ) (c) (d ) (e ) GUI for Next Program – Testing Methods For chars

77  2009 Pearson Education, Inc. All rights reserved. 77 Outline StaticCharMethods.cs (1 of 4 ) Fig. 18.15 | Char’s static character-testing and case-conversion methods. (Part 1 of 4.) Figure 18.15 demonstrates some static methods of the Char struct.

78  2009 Pearson Education, Inc. All rights reserved. 78 Outline StaticCharMethods.cs (2 of 4 ) Fig. 18.15 | Char’s static character-testing and case-conversion methods. (Part 2 of 4.) Char method IsDigit determines whether a character is defined as a digit. IsLetter determines whether a character is a letter. IsLower determines whether a character is a lowercase letter. ToUpper returns a character’s uppercase equivalent, or the original argument if there is no uppercase equivalent. IsUpper determines whether a character is an uppercase letter. IsLetterOrDigit determines whether a character is a letter or a digit.

79  2009 Pearson Education, Inc. All rights reserved. 79 Outline StaticCharMethods.cs (3 of 4 ) Fig. 18.15 | Char’s static character-testing and case-conversion methods. (Part 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 "^".

80  2009 Pearson Education, Inc. All rights reserved. 80 Outline StaticCharMethods.cs (4 of 4 ) Fig. 18.15 | Char’s static character-testing and case-conversion methods. (Part 4 of 4.) (a ) (b ) (c) (d ) (e )

81  2009 Pearson Education, Inc. All rights reserved. 81 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. ** READ LATER **

82  2009 Pearson Education, Inc. All rights reserved. 82 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. ** READ LATER **

83  2009 Pearson Education, Inc. All rights reserved. 83 ** SKIP** >> SELF-STUDY << 18.15 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

84  2009 Pearson Education, Inc. All rights reserved. 84 Outline Card.cs (1 of 2 ) Fig. 18.16 | Card class. (Part 1 of 2.) 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. The constructor for the class receives two string s that it uses to initialize face and suit. ** SKIP **

85  2009 Pearson Education, Inc. All rights reserved. 85 Outline Card.cs (2 of 2 ) Fig. 18.16 | Card class. (Part 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. ** SKIP **

86  2009 Pearson Education, Inc. All rights reserved. 86 Outline DeckForm.cs (1 of 6 ) Fig. 18.17 | Card shuffling and dealing simulation. (Part 1 of 6.) We develop the DeckForm application (Fig. 18.17), which creates a deck of 52 playing cards, using Card objects. ** SKIP **

87  2009 Pearson Education, Inc. All rights reserved. 87 Outline DeckForm.cs (2 of 6 ) Fig. 18.17 | Card shuffling and dealing simulation. (Part 2 of 6.) Each Card is instantiated and initialized with two string s—one from the faces array and one from the suits array. ** SKIP **

88  2009 Pearson Education, Inc. All rights reserved. 88 Outline DeckForm.cs (3 of 6 ) Fig. 18.17 | Card shuffling and dealing simulation. (Part 3 of 6.) ** SKIP **

89  2009 Pearson Education, Inc. All rights reserved. 89 Outline DeckForm.cs (4 of 6 ) Fig. 18.17 | Card shuffling and dealing simulation. (Part 4 of 6.) Swap each card with another randomly chosen card. ** SKIP **

90  2009 Pearson Education, Inc. All rights reserved. 90 Outline DeckForm.cs (5 of 6 ) Fig. 18.17 | Card shuffling and dealing simulation. (Part 5 of 6.) If the deck is not empty, return a Card object reference; otherwise, it returns null. ** SKIP **

91  2009 Pearson Education, Inc. All rights reserved. 91 Outline DeckForm.cs (6 of 6 ) Fig. 18.17 | Card shuffling and dealing simulation. (Part 6 of 6.) (c) (b) (d)(c) (a) ** SKIP **

92  2009 Pearson Education, Inc. All rights reserved. 92 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 ** SKIP **

93  2009 Pearson Education, Inc. All rights reserved. 93 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 whitespaceFollowed by ‘in’ Followed by a whitespaceFollowed by ‘20’ Followed by any digitFollowed 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?) ** SKIP **

94  2009 Pearson Education, Inc. All rights reserved. 94 18.16 Introduction to Regular- Expression Processing SKIP the rest of Section 18.16 ** SKIP **

95  2009 Pearson Education, Inc. All rights reserved. 95 The End of Ch. 18 (ed.3)


Download ppt " 2009 Pearson Education, Inc. All rights reserved. 1 Ch.18 Strings, Characters [and Regular Expressions] Many slides modified by Prof. L. Lilien (even."

Similar presentations


Ads by Google