Strings and Characters in C#: Methods and Constructors, Slides of C programming

Various methods and constructors of the string class in c# programming language. Topics include creating strings using constructors, using methods like toupper, tolower, format, substring, concat, compareto, equals, startswith, endswith, indexof, indexofany, lastindexof, lastindexofany, replace, trim, and various string manipulation methods using stringbuilder.

Typology: Slides

2010/2011

Uploaded on 10/06/2011

christina
christina 🇺🇸

4.6

(23)

393 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS 112 Introduction to
Programming
Lecture #21:
Strings and Characters
http://flint.cs.yale.edu/cs112/
2
Class String
rA string is essentially an encapsulation of an array of characters
msince we use string so often, C# defines the string class and
provides many methods (behaviors)
rWe have already seen several methods
mmethod ToUpper
replaces lower case letter
original string remains unchanged
mmethod ToLower
replaces lower case letter
original string remains unchanged
mMethod Format
rWe will cover some methods; for many other methods, please
read chap. 6 of the textbook and the String method link on the
lecture-notes page
3
Class String: Creating New Strings
rConstructors
mC# provides eight constructors for initializing
strings
rCopyTo method
mcopies specified number of characters into a char
array
rSubstring method
mextracts a sub string
rConcat method
mCombine two strings
Outline
StringConstructo
r.cs
1 // StringConstructor.cs
2 // Demonstrating 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;
17
18 char[] characterArray =
19 { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
20
21 // 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 );
27
28 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
Outline
StringConstructo
r.cs
Program Output
33 MessageBox.Show( output, "String Class Constructors",
34 MessageBoxButtons.OK, MessageBoxIcon.Information );
35
36 } // end method Main
37
38 } // end class StringConstructor
Shows the output
Outline
StringMethods.cs
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;
18
19 string1 = "hello there";
20 characterArray = new char[ 5 ];
21
22 // output string
23 output =
24 "string1: \"" + string1 + "\"";
25
26 // test Length property
27 output += "\nLength of string1: " + string1.Length;
28
29 // loop through character in string1 and display
30 // reversed
31 output += "\nThe string reversed is: ";
32
33 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
pf3
pf4
pf5

Partial preview of the text

Download Strings and Characters in C#: Methods and Constructors and more Slides C programming in PDF only on Docsity!

CS 112 Introduction to

Programming

Lecture #21:

Strings and Characters

http://flint.cs.yale.edu/cs112/

Class String

r A string is essentially an encapsulation of an array of characters

m since we use string so often, C# defines the string class and

provides many methods (behaviors)

r We have already seen several methods

m method ToUpper

  • replaces lower case letter
  • original string remains unchanged

m method ToLower

  • replaces lower case letter
  • original string remains unchanged

m Method Format

r We will cover some methods; for many other methods, please

read chap. 6 of the textbook and the String method link on the

lecture-notes page

Class String: Creating New Strings

r Constructors

m C# provides eight constructors for initializing

strings

r CopyTo method

m copies specified number of characters into a char

array

r Substring method

m extracts a sub string

r Concat method

m Combine two strings

Outline

StringConstructo

r.cs

1 // StringConstructor.cs 2 // Demonstrating 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; 17 18 char[] characterArray = 19 { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' }; 20 21 // 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 ); 27 28 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

Outline

StringConstructo

r.cs

Program Output

33 MessageBox.Show( output, "String Class Constructors", 34 MessageBoxButtons.OK, MessageBoxIcon.Information ); 35 36 } // end method Main 37 38 } // end class StringConstructor

Shows the output

Outline

StringMethods.cs

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; 18 19 string1 = "hello there"; 20 characterArray = new char[ 5 ]; 21 22 // output string 23 output = 24 "string1: "" + string1 + """; 25 26 // test Length property 27 output += "\nLength of string1: " + string1.Length; 28 29 // loop through character in string1 and display 30 // reversed 31 output += "\nThe string reversed is: "; 32 33 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

Outline

StringMethods.cs

Program Output

36 // copy characters from string1 into characterArray 37 string1.CopyTo( 0, characterArray, 0, 5 ); 38 output += "\nThe character array is: "; 39 40 for ( int i = 0 ; i < characterArray.Length; i++ ) 41 output += characterArray[ i ]; 42 43 MessageBox.Show( output, "Demonstrating the string " + 44 "Indexer, Length Property and CopyTo method", 45 MessageBoxButtons.OK, MessageBoxIcon.Information ); 46 47 } // end method Main 48 49 } // 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 string

Outline

SubString.cs

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 = ""; 16 17 // invoke Substring method and pass it one parameter 18 output += "Substring from index 20 to end is "" + 19 letters.Substring( 20 ) + ""\n"; 20 21 // invoke Substring method and pass it two parameters 22 output += "Substring from index 0 to 6 is "" + 23 letters.Substring( 0, 6 ) + """; 24 25 MessageBox.Show( output, 26 "Demonstrating String method Substring", 27 MessageBoxButtons.OK, MessageBoxIcon.Information ); 28 29 } // end method Main 30 31 } // end class SubString

First argument specify

the starting index

Second argument specify

length of the substring to be

copied

Outline

SubString.cs

Program Output

Outline

SubConcatination

.cs

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; 17 18 output = "string1 = "" + string1 + ""\n" + 19 "string2 = "" + string2 + """; 20 21 output += 22 "\n\nResult of String.Concat( string1, string2 ) = " + 23 String.Concat( string1, string2 ); 24 25 output += "\nstring1 after concatenation = " + string1; 26 27 MessageBox.Show( output, 28 "Demonstrating String method Concat", 29 MessageBoxButtons.OK, MessageBoxIcon.Information ); 30 31 } // end method Main 32 33 } // end class StringConcatenation

Declare two new string s

Append string2 unto

the end of string

The original string , string

is not altered

Output the result from the

ConCat method call

Outline

SubConcatination

.cs

Program Output

Class String: Comparison and string Search

r Comparison

m Methods CompareTo and Equals

  • uses lexicographical comparison

m Methods StartsWith and EndsWith

r Find the position of a char or string

m IndexOf

m IndexOfAny

m LastIndexOf

m LastIndexOfAny

Outline

StringIndexMetho

ds.cs

35 output += "\nLast '$' is located at index " + 36 letters.LastIndexOf( '$', 15, 5 ); 37 38 // test IndexOf to locate a substring in a string 39 output += "\n\n"def" is located at" + 40 " index " + letters.IndexOf( "def" ); 41 42 output += "\n"def" is located at index " + 43 letters.IndexOf( "def", 7 ); 44 45 output += "\n"hello" is located at index " + 46 letters.IndexOf( "hello", 5, 15 ); 47 48 // test LastIndexOf to find a substring in a string 49 output += "\n\nLast "def" is located at index " + 50 letters.LastIndexOf( "def" ); 51 52 output += "\nLast "def" is located at " + 53 letters.LastIndexOf( "def", 25 ); 54 55 output += "\nLast "hello" is located at index " + 56 letters.LastIndexOf( "hello", 20, 15 ); 57 58 // test IndexOfAny to find first occurrence of character 59 // in array 60 output += "\n\nFirst occurrence of 'c', 'a', '$' is " + 61 "located at " + letters.IndexOfAny( searchLetters ); 62 63 output += "\nFirst occurrence of 'c, 'a' or '$' is " + 64 "located at " + letters.IndexOfAny( searchLetters, 7 ); 65 66 output += "\nFirst occurrence of 'c', 'a' or '$' is " + 67 "located at " + letters.IndexOfAny( searchLetters, 20, 5 ); 68

Instead of sending character

arguments, these two methods

search substring argument

Method IndexOfAny take

an array of characters as

the first argument; returns

the index of first

occurrence of any

characters specified in the

character array argument

Outline

StringIndexMetho

ds.cs

69 // test LastIndexOfAny to find last occurrence of character 70 // in array 71 output += "\n\nLast occurrence of 'c', 'a' or '$' is " + 72 "located at " + letters.LastIndexOfAny( searchLetters ); 73 74 output += "\nLast occurrence of 'c', 'a' or '$' is " + 75 "located at " + letters.LastIndexOfAny( searchLetters, 1 ); 76 77 output += "\nLast occurrence of 'c', 'a' or '$' is " + 78 "located at " + letters.LastIndexOfAny( 79 searchLetters, 25, 5 ); 80 81 MessageBox.Show( output, 82 "Demonstrating class index methods", 83 MessageBoxButtons.OK, MessageBoxIcon.Information ); 84 85 } // end method Main 86 87 } // end class StringIndexMethods

Outline

StringIndexMetho

ds.cs

Program Output

More String Methods

r Method Trim

m removes whitespaces at the beginning and

end

m original string is changed

r Method Replace

m Change all occurrences of one char or string with

another one

m original string remains unchanged

Outline

StringMiscellane

ous2.cs

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 StringMethods 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; 19 20 output = "string1 = "" + string1 + ""\n" + 21 "string2 = "" + string2 + ""\n" + 22 "string3 = "" + string3 + """; 23 24 // call method Replace 25 output += 26 "\n\nReplacing "e" with "E" in string1: "" + 27 string1.Replace( 'e', 'E' ) + """; 28 29 // 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 string

String to search for String to replace with

Outline

StringMiscellane

ous2.cs

Program Output

34 // call Trim method 35 output += "\n\nstring3 after trim = "" + 36 string3.Trim() + """; 37 38 // call ToString method 39 output += "\n\nstring1 = "" + string1 + """; 40 41 MessageBox.Show( output, 42 "Demonstrating various string methods", 43 MessageBoxButtons.OK, MessageBoxIcon.Information ); 44 45 } // end method Main 46 47 } // end class StringMethods

Method Trim to remove all

whitespace character at the

beginning or end of string3;

Return new string omitting

leading or trailing

whitespace character

Backup Slides

Class StringBuilder

r Class StringBuilder

m Create and manipulate dynamic string information

m Capable of resizing

Outline

StringBuilderCon

structor.cs

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; 17 18 buffer1 = new StringBuilder(); 19 buffer2 = new StringBuilder( 10 ); 20 buffer3 = new StringBuilder( "hello" ); 21 22 output = "buffer1 = "" + buffer1.ToString() + ""\n"; 23 24 output += "buffer2 = "" + buffer2.ToString() + ""\n"; 25 26 output += "buffer3 = "" + buffer3.ToString() + ""\n"; 27 28 MessageBox.Show( output, 29 "Demonstrating StringBuilder class constructors", 30 MessageBoxButtons.OK, MessageBoxIcon.Information ); 31 32 } // end method Main 33 34 } // 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

Outline

StringBuilderCon

structor.cs

Program Output

StringBuilder Indexer, Length and Capacity

Properties, and EnsureCapacity Method

r Method EnsureCapacity

m Allows programmers to guarantee StringBuilder

has capacity that reduces the number of times

capacity must be increased

m Doubles StringBuiler instance’s current

capacity

m Length property returns number of character in

StringBuilder

m Capacity property returns number

StringBuilder can store without allocating

memory

Outline

StringBuilderFea

tures.cs

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?" ); 17 18 // use Length and Capacity properties 19 string output = "buffer = " + buffer.ToString() + 20 "\nLength = " + buffer.Length + 21 "\nCapacity = " + buffer.Capacity; 22 23 // use EnsureCapacity method 24 buffer.EnsureCapacity( 75 ); 25 26 output += "\n\nNew capacity = " + 27 buffer.Capacity; 28 29 // truncate StringBuilder by setting Length property 30 buffer.Length = 10; 31 32 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

StringBuilder Insert, Remove and

Replace Methods

r Insert method

m StringBuilder provides 18 overloaded methods

• Insert into at any position

m Program may throw

ArgumentOutOfRangeException

r Remove method

m Takes two argument

m Program may throw

ArgumentOutOfRangeException

r Replace method

m Substitute specified string

Outline

StringBuilderIns

ertRemove.cs

1 // StringBuilderInsertRemove.cs 2 // Demonstrating methods Insert and Remove of the 3 // StringBuilder class. 4 5 using System; 6 using System.Windows.Forms; 7 using System.Text; 8 9 // test the Insert and Remove methods 10 class StringBuilderInsertRemove 11 { 12 // The main entry point for the application. 13 [STAThread] 14 static void Main( string[] args ) 15 { 16 object objectValue = "hello"; 17 string stringValue = "good bye"; 18 char[] characterArray = { 'a', 'b', 'c', 19 'd', 'e', 'f' }; 20 21 bool booleanValue = true; 22 char characterValue = 'K'; 23 int integerValue = 7; 24 long longValue = 10000000; 25 float floatValue = 2.5F; 26 double doubleValue = 33.333; 27 StringBuilder buffer = new StringBuilder(); 28 string output; 29 30 // insert values into buffer 31 buffer.Insert(0, objectValue); 32 buffer.Insert(0, " "); 33 buffer.Insert(0, stringValue); 34 buffer.Insert(0, " ");

Various different

type of objects

created to append

Uses the Insert method

Outline

StringBuilderIns

ertRemove.cs

35 buffer.Insert(0, characterArray); 36 buffer.Insert(0, " "); 37 buffer.Insert(0, booleanValue); 38 buffer.Insert(0, " "); 39 buffer.Insert(0, characterValue); 40 buffer.Insert(0, " "); 41 buffer.Insert(0, integerValue); 42 buffer.Insert(0, " "); 43 buffer.Insert(0, longValue); 44 buffer.Insert(0, " "); 45 buffer.Insert(0, floatValue); 46 buffer.Insert(0, " "); 47 buffer.Insert(0, doubleValue); 48 buffer.Insert(0, " "); 49 50 output = "buffer after inserts: \n" + 51 buffer.ToString() + "\n\n"; 52 53 buffer.Remove( 10, 1 ); // delete 2 in 2. 54 buffer.Remove( 2, 4 ); // delete .333 in 33. 55 56 output += "buffer after Removes:\n" + 57 buffer.ToString(); 58 59 MessageBox.Show( output, "Demonstrating StringBuilder " + 60 "Insert and Remove methods", MessageBoxButtons.OK, 61 MessageBoxIcon.Information ); 62 63 } // end method Main 64 65 } // end class StringBuilderInsertRemove

Outline

StringBuilderIns

ertRemove.cs

Program Output

Changes to the

string from the

Remove method call

Outline

StringBuilderRep

lace.cs

1 // StringBuilderReplace.cs 2 // Demonstrating method Replace. 3 4 using System; 5 using System.Windows.Forms; 6 using System.Text; 7 8 // testing the Replace method 9 class StringBuilderReplace 10 { 11 // The main entry point for the application. 12 [STAThread] 13 static void Main( string[] args ) 14 { 15 StringBuilder builder1 = 16 new StringBuilder( "Happy Birthday Jane" ); 17 18 StringBuilder builder2 = 19 new StringBuilder( "good bye greg" ); 20 21 string output = "Before replacements:\n" + 22 builder1.ToString() + "\n" + builder2.ToString(); 23 24 builder1.Replace( "Jane", "Greg" ); 25 builder2.Replace( 'g', 'G', 0, 5 ); 26 27 output += "\n\nAfter replacements:\n" + 28 builder1.ToString() + "\n" + builder2.ToString(); 29

StringBuilder created

with specified string s

Replace “Jane” with “Greg”

Replaces all instances of the

first character with the second

Index specify begin point

and continuation span

Outline

StringBuilderRep

lace.cs

Program Output

30 MessageBox.Show( output, 31 "Using StringBuilder method Replace", 32 MessageBoxButtons.OK, MessageBoxIcon.Information ); 33 34 } // end method Main 35 36 } // end class StringBuilderReplace

Result from replacing “Jane” with

“Greg”

The continuation span of five was

insufficient for “greg” to be altered