Lecture 10 Dr. Eng. Ibrahim El-Nahry Strings, Characters and Regular Expressions.

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

 2002 Prentice Hall. All rights reserved. 1 Chapter 15 – Strings, Characters and Regular Expressions Outline 15.1Introduction 15.2 Fundamentals of Characters.
 2002 Prentice Hall. All rights reserved. 1 Chapter 15 – Strings, Chars Outline 15.1 Introduction 15.2 Fundamentals of Characters and String s 15.3 String.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Strings in Java 1. strings in java are handled by two classes String &
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Java Programming Strings Chapter 7.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
 2002 Prentice Hall. All rights reserved. 1 Chapter 15 – Strings, Chars and Reg Exp’s Outline 15.1 Introduction 15.2 Fundamentals of Characters and String.
Chapter 15 Strings String::Concat String::CompareTo, Equals, == If( string1 == S”Hello”) String1->Equals(S”Hello”) String1->CompareTo(S”Hello”) CompareTo.
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
Fundamental Programming Structures in Java: Strings.
 2006 Pearson Education, Inc. All rights reserved Strings, Characters and Regular Expressions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
 Pearson Education, Inc. All rights reserved Strings, Characters and Regular Expressions.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 12 More.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 11 – Strings and Characters Outline 11.1 Introduction 11.2 Fundamentals of Characters and Strings.
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
1 Chapter 10 Characters, Strings, and the string class.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
COMPUTER PROGRAMMING I Objective 7.04 Apply Built-in String Functions (3%)
Array String String Builder. Arrays Arrays are collections of several elements of the same type E.g. 100 integers, 20 strings, 125 students, 12 dates,
CSCI 3327 Visual Basic Chapter 12: Strings, Characters and Regular Expressions UTPA – Fall 2011.
Chapter : STRING. Slide 2 9:06:37 AM 1. Introduction String and character processing capabilities –Text editors –Word processors… Expand from previous.
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
CSCI 3327 Visual Basic Chapter 12: Strings, Characters and Regular Expressions UTPA – Fall 2011.
Characters, Strings, And The string Class Chapter 10.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
String String Builder. System.String string is the alias for System.String A string is an object of class string in the System namespace representing.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 10 Characters, Strings, and the string class.
String 1. 2 Char Methods For the char value type, there is a Char class Most methods are static –IsLetter –IsDigit –IsLetterOrDigit –IsLower –IsUpper.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 – Strings and Characters Outline 11.1 Introduction 11.2 Fundamentals of Characters and Strings.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Strings, and the string Class. C-Strings C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character The C-string.
 2009 Pearson Education, Inc. All rights reserved. 1 Ch.18 Strings, Characters [and Regular Expressions] Many slides modified by Prof. L. Lilien (even.
Objective 7.04 Apply Built-in String Functions (3%)
C-Strings We have already seen that a C-string is a null-terminated array of characters.
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Strings.
EKT 472: Object Oriented Programming
Strings, Characters and Regular Expressions
Strings and Characters
String and String Buffers
String String Builder.
Characters, C-Strings, and More About the string Class
Primitive Types Vs. Reference Types, Strings, Enumerations
Standard Version of Starting Out with C++, 4th Edition
Modern Programming Tools And Techniques-I Lecture 11: String Handling
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
10.1 Character Testing.
Strings and Characters
Java – String Handling.
Lecture 07 String Jaeki Song.
Standard Version of Starting Out with C++, 4th Edition
Dr. Sampath Jayarathna Cal Poly Pomona
Visual Programming COMP-315
String Manipulation.
In Java, strings are objects that belong to class java.lang.String .
Unit-2 Objects and Classes
Presentation transcript:

Lecture 10 Dr. Eng. Ibrahim El-Nahry Strings, Characters and Regular Expressions

2 Class String A string is essentially an encapsulation of an array of characters since we use string so often, C# defines the string class and provides many methods (behaviors) We have already seen several methods method ToUpper replaces lower case letter original string remains unchanged method ToLower replaces lower case letter original string remains unchanged Method Format

3 Class String: Creating New Strings Constructors C# provides eight constructors for initializing strings CopyTo method copies specified number of characters into a char array Substring method extracts a sub string Concat method Combine two strings

The Eight String Constructors 4

The String Constructor The String class itself has eight constructors. If you look in the Object Browser, you can see that five of these use pointers and are not safe under the rules of the Common Language Specification (CLS) that.NET languages must follow. We will only discuss the three constructors. One possible use is creating a string containing one char repeated many times. Another is converting a char array into a string. 5

6 1 // StringConstructor.cs 2 // Demonstrating the use of three String class constructors. 3 4 using System; 5 using System.Windows.Forms; 6 7 // test several String class constructors 8 class StringConstructor 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string[] args ) 13 { 14 string output; 15 string originalString, string1, string2, 16 string3, string4; char[] characterArray = 19 { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' }; // string initialization 22 originalString = "Welcome to C# programming!"; 23 string1 = originalString; 24 string2 = new string( characterArray ); 25 string3 = new string( characterArray, 6, 3 ); 26 string4 = new string( 'C', 5 ); output = "string1 = " + "\"" + string1 + "\"\n" + 29 "string2 = " + "\"" + string2 + "\"\n" + 30 "string3 = " + "\"" + string3 + "\"\n" + 31 "string4 = " + "\"" + string4 + "\"\n"; 32 String constructor takes a character array as argument String constructor takes a char array and two int arguments Starting index and count Using string constructed with a character and an int specifying number of times to repeat character in the string

7 rogram Output 33 MessageBox.Show( output, "String Class Constructors", 34 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringConstructor Shows the output

8 1 // StringMethods.cs 2 // Using the indexer, property Length and method CopyTo 3 // of class String. 4 5 using System; 6 using System.Windows.Forms; 7 8 // creates string objects and displays results of using 9 // indexer and methods Length and CopyTo 10 class StringMethods 11 { 12 // The main entry point for the application. 13 [STAThread] 14 static void Main( string[] args ) 15 { 16 string string1, output; 17 char[] characterArray; string1 = "hello there"; 20 characterArray = new char[ 5 ]; // output string 23 output = 24 "string1: \"" + string1 + "\""; // test Length property 27 output += "\nLength of string1: " + string1.Length; // loop through character in string1 and display 30 // reversed 31 output += "\nThe string reversed is: "; for ( int i = string1.Length - 1; i >= 0; i-- ) 34 output += string1[ i ]; 35 String declarations String1 to store string literal “hello there” Append to output of string1 in reverse order

9 Program Output 36 // copy characters from string1 into characterArray 37 string1.CopyTo( 0, characterArray, 0, 5 ); 38 output += "\nThe character array is: "; for ( int i = 0 ; i < characterArray.Length; i++ ) 41 output += characterArray[ i ]; MessageBox.Show( output, "Demonstrating the string " + 44 "Indexer, Length Property and CopyTo method", 45 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringMethods Index to begin copying character array to copy to Index of location to put into character array Number of characters to copy from string Method Copyto called by string1

10 1 // SubString.cs 2 // Demonstrating the String Substring method. 3 4 using System; 5 using System.Windows.Forms; 6 7 // creating substrings 8 class SubString 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string[] args ) 13 { 14 string letters = "abcdefghijklmabcdefghijklm"; 15 string output = ""; // invoke Substring method and pass it one parameter 18 output += "Substring from index 20 to end is \"" + 19 letters.Substring( 20 ) + "\"\n"; // invoke Substring method and pass it two parameters 22 output += "Substring from index 0 to 6 is \"" + 23 letters.Substring( 0, 6 ) + "\""; MessageBox.Show( output, 26 "Demonstrating String method Substring", 27 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class SubString First argument specify the starting index Second argument specify length of the substring to be copied

11 Program Output

12 1 // SubConcatination.cs 2 // Demonstrating String class Concat method. 3 4 using System; 5 using System.Windows.Forms; 6 7 // concatenates strings using String method Concat 8 class StringConcatenation 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string[] args ) 13 { 14 string string1 = "Happy "; 15 string string2 = "Birthday"; 16 string output; output = "string1 = \"" + string1 + "\"\n" + 19 "string2 = \"" + string2 + "\""; output += 22 "\n\nResult of String.Concat( string1, string2 ) = " + 23 String.Concat( string1, string2 ); output += "\nstring1 after concatenation = " + string1; MessageBox.Show( output, 28 "Demonstrating String method Concat", 29 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringConcatenation Declare two new stringsAppend string2 unto the end of string1 The original string, string1 is not altered Output the result from the ConCat method call

13 Program Output

14 Class String: Comparison and string Search Comparison Methods CompareTo and Equals uses lexicographical comparison Methods StartsWith and EndsWith Find the position of a char or string IndexOf IndexOfAny LastIndexOf LastIndexOfAny

15 1 // Fig. StringCompare.cs 2 // Comparing strings. 3 4 using System; 5 using System.Windows.Forms; 6 7 // compare a number of strings 8 class StringCompare 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string[] args ) 13 { 14 string string1 = "hello"; 15 string string2 = "good bye"; 16 string string3 = "Happy Birthday"; 17 string string4 = "happy birthday"; 18 string output; // output values of four strings 21 output = "string1 = \"" + string1 + "\"" + 22 "\nstring2 = \"" + string2 + "\"" + 23 "\nstring3 = \"" + string3 + "\"" + 24 "\nstring4 = \"" + string4 + "\"\n\n"; // test for equality using Equals method 27 if ( string1.Equals( "hello" ) ) 28 output += "string1 equals \"hello\"\n"; 29 else 30 output += "string1 does not equal \"hello\"\n"; // test for equality with == 33 if ( string1 == "hello" ) 34 output += "string1 equals \"hello\"\n"; Instance method Equals Equality operator

16 35 else 36 output += "string1 does not equal \"hello\"\n"; // test for equality comparing case 39 if ( String.Equals( string3, string4 ) ) 40 output += "string3 equals string4\n"; 41 else 42 output += "string3 does not equal string4\n"; // test CompareTo 45 output += "\nstring1.CompareTo( string2 ) is " + 46 string1.CompareTo( string2 ) + "\n" + 47 "string2.CompareTo( string1 ) is " + 48 string2.CompareTo( string1 ) + "\n" + 49 "string1.CompareTo( string1 ) is " + 50 string1.CompareTo( string1 ) + "\n" + 51 "string3.CompareTo( string4 ) is " + 52 string3.CompareTo( string4 ) + "\n" + 53 "string4.CompareTo( string3 ) is " + 54 string4.CompareTo( string3 ) + "\n\n"; MessageBox.Show( output, "Demonstrating string " + 57 "comparisons", MessageBoxButtons.OK, 58 MessageBoxIcon.Information ); } // end method Main } // end class StringCompare Static method Equals Method CompareTo called to compare strings

17 Program Output

18 1 // StringStartEnd.cs 2 // Demonstrating StartsWith and EndsWith methods. 3 4 using System; 5 using System.Windows.Forms; 6 7 // testing StartsWith and EndsWith 8 class StringStartEnd 9 { 10 // The main entry point for the application. 11 [STAThread] 12 static void Main( string[] args ) 13 { 14 string[] strings = 15 { "started", "starting", "ended", "ending" }; 16 string output = ""; //test every string to see if it starts with "st" 19 for ( int i = 0; i < strings.Length; i++ ) if ( strings[ i ].StartsWith( "st" ) ) 22 output += "\"" + strings[ i ] + "\"" + 23 " starts with \"st\"\n"; output += "\n"; // test every string to see if it ends with "ed" 28 for ( int i = 0; i < strings.Length; i ++ ) if ( strings[ i ].EndsWith( "ed" ) ) 31 output += "\"" + strings[ i ] + "\"" + 32 " ends with \"ed\"\n"; 33 Method StartsWith determines if a string instance starts with the string text passed to it Method EndsWith determines if a string instance ends with the string text passed to it Array of strings; contents defined at time of declaration

19 Program Output 34 MessageBox.Show( output, "Demonstrating StartsWith and " + 35 "EndsWith methods", MessageBoxButtons.OK, 36 MessageBoxIcon.Information ); } // end method Main } // end class StringStartEnd

Locating Characters and Substrings in Strings Application of String methods: IndexOf IndexOfAny LastIndexOf LastIndexOfAny 20

using System; using System.Windows.Forms; // testing indexing capabilities of strings class StringIndexMethods { // The main entry point for the application. [STAThread] static void Main( string[] args ) { string letters = "abcdefghijklmabcdefghijklm"; string output = ""; char[] searchLetters = { 'c', 'a', '$' }; // test IndexOf to locate a character in a string output += "'c' is located at index " + letters.IndexOf( 'c' ); output += "\n'a' is located at index " + letters.IndexOf( 'a', 1 ); output += "\n'$' is located at index " + letters.IndexOf( '$', 3, 5 ); // test LastIndexOf to find a character in a string output += "\n\nLast 'c' is located at " + "index " + letters.LastIndexOf( 'c' ); output += "\nLast 'a' is located at index " + letters.LastIndexOf( 'a', 25 ); 21

output += "\nLast '$' is located at index " + letters.LastIndexOf( '$', 15, 5 ); // test IndexOf to locate a substring in a string output += "\n\n\"def\" is located at" + " index " + letters.IndexOf( "def" ); output += "\n\"def\" is located at index " + letters.IndexOf( "def", 7 ); output += "\n\"hello\" is located at index " + letters.IndexOf( "hello", 5, 15 ); // test LastIndexOf to find a substring in a string output += "\n\nLast \"def\" is located at index " + letters.LastIndexOf( "def" ); output += "\nLast \"def\" is located at " + letters.LastIndexOf( "def", 25 ); output += "\nLast \"hello\" is located at index " + letters.LastIndexOf( "hello", 20, 15 ); // test IndexOfAny to find first occurrence of character // in array output += "\n\nFirst occurrence of 'c', 'a', '$' is " + "located at " + letters.IndexOfAny( searchLetters ); output += "\nFirst occurrence of 'c, 'a' or '$' is " + "located at " + letters.IndexOfAny( searchLetters, 7 ); output += "\nFirst occurrence of 'c', 'a' or '$' is " + "located at " + letters.IndexOfAny( searchLetters, 20, 5 ); 22

// test LastIndexOfAny to find last occurrence of character // in array output += "\n\nLast occurrence of 'c', 'a' or '$' is " + "located at " + letters.LastIndexOfAny( searchLetters ); output += "\nLast occurrence of 'c', 'a' or '$' is " + "located at " + letters.LastIndexOfAny( searchLetters, 1 ); output += "\nLast occurrence of 'c', 'a' or '$' is " + "located at " + letters.LastIndexOfAny( searchLetters, 25, 5 ); MessageBox.Show( output, "Demonstrating class index methods", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringIndexMethods 23

24

25 More String Methods Method Trim removes whitespaces at the beginning and end original string is changed Method Replace Change all occurrences of one char or string with another one original string remains unchanged

26 1 // StringMethod2.cs 2 // Demonstrating String methods Replace, ToLower, ToUpper, Trim 3 // and ToString. 4 5 using System; 6 using System.Windows.Forms; 7 8 // creates strings using methods Replace, ToLower, ToUpper, Trim 9 class StringMethods2 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string[] args ) 14 { 15 string string1 = "cheers!"; 16 string string2 = "GOOD BYE "; 17 string string3 = " spaces "; 18 string output; output = "string1 = \"" + string1 + "\"\n" + 21 "string2 = \"" + string2 + "\"\n" + 22 "string3 = \"" + string3 + "\""; // call method Replace 25 output += 26 "\n\nReplacing \"e\" with \"E\" in string1: \"" + 27 string1.Replace( 'e', 'E' ) + "\""; // call ToLower and ToUpper 30 output += "\n\nstring1.ToUpper() = \"" + 31 string1.ToUpper() + "\"\nstring2.ToLower() = \"" + 32 string2.ToLower() + "\""; 33 Method Replace return new string with correct revision based on the argument Replace all instances of ‘e’ with ‘E’ in string1 String to search forString to replace with

27 Program Output 34 // call Trim method 35 output += "\n\nstring3 after trim = \"" + 36 string3.Trim() + "\""; // call ToString method 39 output += "\n\nstring1 = \"" + string1 + "\""; MessageBox.Show( output, 42 "Demonstrating various string methods", 43 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringMethods2 Method Trim to remove all whitespace character at the beginning or end of string3; Return new string omitting leading or trailing whitespace character

28 Class StringBuilder Create and manipulate dynamic string information Capable of resizing

29 1 // StringBuilderConstructor.cs 2 // Demonstrating StringBuilder class constructors. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text; 7 8 // creates three StringBuilder with three constructors 9 class StringBuilderConstructor 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string[] args ) 14 { 15 StringBuilder buffer1, buffer2, buffer3; 16 string output; buffer1 = new StringBuilder(); 19 buffer2 = new StringBuilder( 10 ); 20 buffer3 = new StringBuilder( "hello" ); output = "buffer1 = \"" + buffer1.ToString() + "\"\n"; output += "buffer2 = \"" + buffer2.ToString() + "\"\n"; output += "buffer3 = \"" + buffer3.ToString() + "\"\n"; MessageBox.Show( output, 29 "Demonstrating StringBuilder class constructors", 30 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringBuilderConstructor No-argument StringBuilder constructor with default initial capacity at 16 Initial capacity is the smallest power of two greater than the number of characters in the string argument Method ToString to obtain string representation of the StringBuilders’ content; Method returns the StringBuilders’ underlying string

30 Program Output

31 StringBuilder Indexer, Length and Capacity Properties, and EnsureCapacity Method Method EnsureCapacity Allows programmers to guarantee StringBuilder has capacity that reduces the number of times capacity must be increased Doubles StringBuiler instance’s current capacity Length property returns number of character in StringBuilder Capacity property returns number StringBuilder can store without allocating memory

32 1 // StringBuilderFeatures.cs 2 // Demonstrating some features of class StringBuilder. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text; 7 8 // uses some of class StringBuilder ’ s methods 9 class StringBuilderFeatures 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string[] args ) 14 { 15 StringBuilder buffer = 16 new StringBuilder( "Hello, how are you?" ); // use Length and Capacity properties 19 string output = "buffer = " + buffer.ToString() + 20 "\nLength = " + buffer.Length + 21 "\nCapacity = " + buffer.Capacity; // use EnsureCapacity method 24 buffer.EnsureCapacity( 75 ); output += "\n\nNew capacity = " + 27 buffer.Capacity; // truncate StringBuilder by setting Length property 30 buffer.Length = 10; output += "\n\nNew length = " + 33 buffer.Length + "\nbuffer = "; 34 Declare a StringBuilder name buffer Take string argument to initialize its value to the actual string Append to output the length of StringBuilder Append to output the capacity of StringBuilder Expands the capacity to a minimum of 75 characters Uses Length’s Set accessor to set length of the Stringbuilder to 10

New length allow for the StringBuilder to be of only 10, truncate any preceding characters for ( int i = 0; i < buffer.Length; i++ ) output += buffer[ i ]; MessageBox.Show( output, "StringBuilder features", MessageBoxButtons.OK, MessageBoxIcon.Information ); }

34 StringBuilder Append and AppendFormat Methods Append method Allow various data-type values to append to the end of a StringBuilder Convert argument into string AppendFormat method Convert string to a specifiable format

35. using System; using System.Windows.Forms; using System.Text; // testing the Append method class StringBuilderAppend { // The main entry point for the application. [STAThread] static void Main( string[] args ) { object objectValue = "hello"; string stringValue = "good bye"; char[] characterArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; bool booleanValue = true; char characterValue = 'Z'; int integerValue = 7; long longValue = ; float floatValue = 2.5F; double doubleValue = ; StringBuilder buffer = new StringBuilder(); // use method Append to append values to buffer buffer.Append( objectValue ); buffer.Append( " " ); buffer.Append( stringValue ); buffer.Append( " " ); buffer.Append( characterArray ); buffer.Append( " " );

36. buffer.Append( characterArray, 0, 3 ); buffer.Append( " " ); buffer.Append( booleanValue ); buffer.Append( " " ); buffer.Append( characterValue ); buffer.Append( " " ); buffer.Append( integerValue ); buffer.Append( " " ); buffer.Append( longValue ); buffer.Append( " " ); buffer.Append( floatValue ); buffer.Append( " " ); buffer.Append( doubleValue ); MessageBox.Show( "buffer = " + buffer.ToString(), "Demonstrating StringBuilder append method", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringBuilderAppend

37 using System; using System.Windows.Forms; using System.Text; // use the AppendFormat method class StringBuilderAppendFormat { // The main entry point for the application. [STAThread] static void Main( string[] args ) { StringBuilder buffer = new StringBuilder(); string string1, string2; // formatted string string1 = "This {0} costs: {1:C}.\n"; // string1 argument array object[] objectArray = new object[ 2 ]; objectArray[ 0 ] = "car"; objectArray[ 1 ] = ; // append to buffer formatted string with argument buffer.AppendFormat( string1, objectArray ); // formatted string string2 = "Number:{0:d3}.\n" + "Number right aligned with spaces:{0, 4}.\n" + "Number left aligned with spaces:{0, -4}.";

38 // append to buffer formatted string with argument buffer.AppendFormat( string2, 5 ); // display formatted strings MessageBox.Show( buffer.ToString(), "Using AppendFormat", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringBuilderAppendFormat

39 StringBuilder Insert, Remove and Replace Methods Insert method StringBuilder provides 18 overloaded methods Insert into at any position Program may throw ArgumentOutOfRangeException Remove method Takes two argument ( the index at which to begin deletion and the number of characters to delete). Program may throw ArgumentOutOfRangeException Replace method Substitute specified string

40 using System; using System.Windows.Forms; using System.Text; // test the Insert and Remove methods class StringBuilderInsertRemove { // The main entry point for the application. [STAThread] static void Main( string[] args ) { object objectValue = "hello"; string stringValue = "good bye"; char[] characterArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; bool booleanValue = true; char characterValue = 'K'; int integerValue = 7; long longValue = ; float floatValue = 2.5F; double doubleValue = ; StringBuilder buffer = new StringBuilder(); string output; // insert values into buffer buffer.Insert(0, objectValue); buffer.Insert(0, " "); buffer.Insert(0, stringValue); buffer.Insert(0, " ");

buffer.Insert(0, characterArray); buffer.Insert(0, " "); buffer.Insert(0, booleanValue); buffer.Insert(0, " "); buffer.Insert(0, characterValue); buffer.Insert(0, " "); buffer.Insert(0, integerValue); buffer.Insert(0, " "); buffer.Insert(0, longValue); buffer.Insert(0, " "); buffer.Insert(0, floatValue); buffer.Insert(0, " "); buffer.Insert(0, doubleValue); buffer.Insert(0, " "); output = "buffer after inserts: \n" + buffer.ToString() + "\n\n"; buffer.Remove( 10, 1 ); // delete 2 in 2.5 buffer.Remove( 2, 4 ); // delete.333 in output += "buffer after Removes:\n" + buffer.ToString(); MessageBox.Show( output, "Demonstrating StringBuilder " + "Insert and Remove methods", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringBuilderInsertRemove

43 using System; using System.Windows.Forms; using System.Text; // testing the Replace method class StringBuilderReplace { // The main entry point for the application. [STAThread] static void Main( string[] args ) { StringBuilder builder1 = new StringBuilder( "Happy Birthday Jane" ); StringBuilder builder2 = new StringBuilder( "good bye greg" ); string output = "Before replacements:\n" + builder1.ToString() + "\n" + builder2.ToString(); builder1.Replace( "Jane", "Greg" ); builder2.Replace( 'g', 'G', 0, 5 ); output += "\n\nAfter replacements:\n" + builder1.ToString() + "\n" + builder2.ToString();

44 MessageBox.Show( output, "Using StringBuilder method Replace", MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // end class StringBuilderReplace

Char Methods Structure Char For character usage Most methods are static Methods: IsLower IsUpper ToUpper ToLower IsPunctuation IsSymbol IsWhiteSpace 45

Program that tests char.IsPunctuation 46 using System; class Program { static void Main() { for (int i = 0; i < 128; i++) { if (char.IsPunctuation((char)i)) { Console.WriteLine("case '{0}':", (char)i); } Output case '!': case '"': case '#': case '%': case '&': case ''': case '(': case ')': case '*': case ',': case '-': case '.': case '/': case ':': case ';': case '?': case case '[': case '\': case ']': case '_': case '{': case '}':

47 using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; // Form displays information about specific characters. public class StaticCharMethods : System.Windows.Forms.Form { private System.Windows.Forms.Label enterLabel; private System.Windows.Forms.TextBox inputTextBox; private System.Windows.Forms.Button analyzeButton; private System.Windows.Forms.TextBox outputTextBox; private System.ComponentModel.Container components = null; // The main entry point for the application. [STAThread] static void Main() { Application.Run( new StaticCharMethods() ); } // Visual Studio.NET generated code TextBox for user to input characters TextBox to displays the output of analysis

48 // handle analyzeButton_Click private void analyzeButton_Click( object sender, System.EventArgs e ) { char character = Convert.ToChar( inputTextBox.Text ); BuildOutput( character ); } // display character information in outputTextBox private void BuildOutput( char inputCharacter ) { string output; output = "is digit: " + Char.IsDigit( inputCharacter ) + "\r\n"; output += "is letter: " + Char.IsLetter( inputCharacter ) + "\r\n"; output += "is letter or digit: " + Char.IsLetterOrDigit( inputCharacter ) + "\r\n"; output += "is lower case: " + Char.IsLower( inputCharacter ) + "\r\n"; output += "is upper case: " + Char.IsUpper( inputCharacter ) + "\r\n"; output += "to upper case: " + Char.ToUpper( inputCharacter ) + "\r\n"; output += "to lower case: " + Char.ToLower( inputCharacter ) + "\r\n"; Event handler invoke when user click Analyze Character Convert entered data from a string to a Char Method Convert.ToChar Method BuildOutputChar method IsDigit, return true if inputCharacter is define as a digit Char method IsLetter return true if inputCharacter is a letter Char method IsLetterOrDigit return true if inputCharacter is a letter or digit Char method IsLower return true if inputCharacter is a lowercase letter Char method IsUpper return true if inputCharacter is an uppercase letter Char method ToUpper convert inputCharacter to uppercase equivalent Char method ToLower convert inputCharacter to lowercase equivalent Method will return original argument if no conversion made 48

49 output += "is punctuation: " + Char.IsPunctuation( inputCharacter ) + "\r\n"; output += "is symbol: " + Char.IsSymbol( inputCharacter ); outputTextBox.Text = output; } // end method BuildOutput } // end class StaticCharMethods Char method IsPunctuation return true if inputCharacter is a punctuation mark Char method IsSymbol return true if inputCharacter is a symbol