MI KE
TM approved
204111 Computer and Programming
Lecture # 09:
Strings and Characters Name Spaces, Enum, Struct Try-Catch Block
http: / / mike.cpe.ku.ac.th/ 204111
204111 Computer and Programming Lecture # 09: Strings and - - PowerPoint PPT Presentation
204111 Computer and Programming Lecture # 09: Strings and Characters Name Spaces, Enum, Struct Try-Catch Block http: / / mike.cpe.ku.ac.th/ 204111 TM approved MI KE Class String A string is essentially an encapsulation of an array of
MI KE
TM approved
Strings and Characters Name Spaces, Enum, Struct Try-Catch Block
http: / / mike.cpe.ku.ac.th/ 204111
2 MI KE
TM approved
Version 2005/2
A string is essentially an encapsulation of
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
method ToLower
replaces lower case letter
3 MI KE
TM approved
Version 2005/2
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.
4 MI KE
TM approved
Version 2005/2
using System; using System.Windows.Forms; class StringConstructor { static void Main( string [] args ) { string output; string originalString, string1, string2, string3, string4; char [] characterArray = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' }; // string initialization
string1 = originalString; string2 = new string( characterArray ); string3 = new string( characterArray, 6, 3 ); string4 = new string( 'C', 5 ); // combined output
"string2 = " + "\"" + string2 + "\"\n" + "string3 = " + "\"" + string3 + "\"\n" + "string4 = " + "\"" + string4 + "\"\n"; MessageBox.Show( output, "String Class Constructors", MessageBoxButtons.OK, MessageBoxIcon.Information ); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
5 MI KE
TM approved
Version 2005/2
6 MI KE
TM approved
Version 2005/2
using System; using System.Windows.Forms; class StringMethods { static void Main(string [] args ) { string string1, output; char [] characterArray; string1 = "hello there"; characterArray = new char [5];
for ( int i = string1.Length - 1; i >= 0; i-- )
string1.CopyTo(0, characterArray, 0, 5);
for ( int i = 0 ; i < characterArray.Length; i++ )
MessageBox.Show(output, "Demonstrating the string " + "Indexer, Length Property and CopyTo method", MessageBoxButtons.OK, MessageBoxIcon.Information); } // end method Main } // end class StringMethods 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
7 MI KE
TM approved
Version 2005/2
8 MI KE
TM approved
Version 2005/2
using System; using System.Windows.Forms; class SubString { static void Main(string [] args) { string letters = "abcdefghijklmabcdefghijklm"; string output = "";
+ letters.Substring(20) + "\"\n";
+ letters.Substring(0, 6) + "\""; MessageBox.Show(output, "Demonstrating String method Substring", MessageBoxButtons.OK, MessageBoxIcon.Information); } // end method Main } // end class SubString 1 2 3 4 5 6 7 8 9 10 11
9 MI KE
TM approved
Version 2005/2
10 MI KE
TM approved
Version 2005/2
using System; using System.Windows.Forms; class StringConcatenation { static void Main(string [] args) { string string1 = "Happy "; string string2 = "Birthday"; string output;
+ String.Concat(string1, string2);
MessageBox.Show(output, "Demonstrating String method Concat", MessageBoxButtons.OK, MessageBoxIcon.Information); } // end method Main } // end class StringConcatenation 1 2 3 4 5 6 7 8 9 10 11 12 13
11 MI KE
TM approved
Version 2005/2
12 MI KE
TM approved
Version 2005/2
Comparison
Methods CompareTo and Equals
uses lexicographical comparison.
Methods StartsWith and EndsWith
Find the position of a char or string
IndexOf IndexOfAny LastIndexOf LastIndexOfAny
13 MI KE
TM approved
Version 2005/2
using System; using System.Windows.Forms; class StringCompare { static void Main(string [] args) { string string1 = "hello"; string string2 = "good bye"; string string3 = "Happy Birthday"; string string4 = "happy birthday"; string output;
"\nstring3 = \"" + string3 + "\"" + "\nstring4 = \"" + string4 + "\"\n\n"; if (string1.Equals("hello")) output += "string1 equals \"hello\"\n"; else output += "string1 does not equal \"hello\"\n"; if (string1 == "hello") output += "string1 equals \"hello\"\n"; else output += "string1 does not equal \"hello\"\n"; if (String.Equals(string3, string4)) output += "string3 equals string4\n"; else output += "string3 does not equal string4\n";
"string2.CompareTo(string1) is " + string2.CompareTo(string1) + "\n" + "string1.CompareTo(string1) is " + string1.CompareTo(string1) + "\n" + "string3.CompareTo(string4) is " + string3.CompareTo(string4) + "\n" + "string4.CompareTo( string3 ) is " + string4.CompareTo(string3) + "\n\n"; MessageBox.Show(output, "Demonstrating string " + "comparisons", MessageBoxButtons.OK, MessageBoxIcon.Information); } // end method Main } // end class StringCompare 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
14 MI KE
TM approved
Version 2005/2
15 MI KE
TM approved
Version 2005/2
using System; using System.Windows.Forms; class StringStartEnd { static void Main(string [] args) { string [] strings = {"started", "starting", "ended", "ending"}; string output = ""; for (int i = 0; i < strings.Length; i++) if (strings[i].StartsWith("st"))
for (int i = 0; i < strings.Length; i ++) if (strings[i].EndsWith("ed"))
MessageBox.Show(output, "Demonstrating StartsWtih and " + "EndsWith methods", MessageBoxButtons.OK, MessageBoxIcon.Information); } // end method Main } // end class StringStartEnd 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
16 MI KE
TM approved
Version 2005/2
17 MI KE
TM approved
Version 2005/2
using System; using System.Windows.Forms; class StringIndexMethods { static void Main(string [] args) { string letters = "abcdefghijklmabcdefghijklm"; string output = ""; char [] searchLetters = {'c', 'a', '$'};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 MI KE
TM approved
Version 2005/2
letters.LastIndexOf("hello", 20, 15);
letters.IndexOfAny(searchLetters);
letters.IndexOfAny(searchLetters, 7);
letters.IndexOfAny(searchLetters, 20, 5);
letters.LastIndexOfAny(searchLetters);
letters.LastIndexOfAny(searchLetters, 1);
letters.LastIndexOfAny(searchLetters, 25, 5); MessageBox.Show(output, "Demonstrating class index methods", MessageBoxButtons.OK, MessageBoxIcon.Information); } // end method Main } // end class StringIndexMethods 18 19 20 21 22 23 24 25 26 27
19 MI KE
TM approved
Version 2005/2
20 MI KE
TM approved
Version 2005/2
Method Trim
removes whitespaces at the beginning and
end.
Method Replace
changes all occurrences of one char or string
with another one.
21 MI KE
TM approved
Version 2005/2
using System; using System.Windows.Forms; class StringMethods2 { static void Main(string [] args) { string string1 = "cheers!"; string string2 = "GOOD BYE "; string string3 = " spaces "; string output;
string2 + "\"\n" + "string3 = \"" + string3 + "\"";
string1.Replace('e', 'E') + "\"";
"\"\nstring2.ToLower() = \"" + string2.ToLower() + "\"";
MessageBox.Show(output, "Demonstrating various string methods", MessageBoxButtons.OK, MessageBoxIcon.Information); } // end method Main } // end class StringMethods2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
22 MI KE
TM approved
Version 2005/2
23 MI KE
TM approved
Version 2005/2
allows us to use members of the System namespace.
help you organize your programs.
They provide assistance in avoiding name clashes
between two sets of code.
Implementing Namespaces in your own code is a good
habit because it is likely to save you from problems later when you want to reuse some of your code.
names.
If naming directories and files to correspond to
namespaces helps you organize your code, then you may do so, but it is not required.
24 MI KE
TM approved
Version 2005/2
// Namespace Declaration using System; namespace csharp_station {
// nested namespace
namespace tutorial { class myExample1 { public static void myPrint1() { Console.WriteLine("First Example
} } } // Program start class class NamespaceCalling { // Main begins program execution. public static void Main() {
// Write to console
tutorial.myExample1.myPrint1(); tutorial.myExample2.myPrint2(); }
} } // code from the next page follows…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
language element from the namespace name down to the method call.
with class myExample1 and method myPrint1.
in the fully qualified name is unnecessary.
25 MI KE
TM approved
Version 2005/2
24 25 26 27 28 29 30 31 32
tutorial.myExample2.myPrint2().
namespace csharp_station does not need to be a part of the fully qualified name. This is because both classes belong to the same namespace, csharp_station.
because every namespace member of the same type must have a unique name.
// same namespace as nested previous namespace namespace csharp_station.tutorial { class myExample2 { public static void myPrint2() { Console.WriteLine("Second Example of calling another namespace member."); } } }
26 MI KE
TM approved
Version 2005/2
// Namespace Declaration using System; using csTut = csharp_station.tutorial.myExample; // Program start class class AliasDirective { // Main begins program execution. public static void Main() { // Call namespace member csTut.myPrint(); myPrint(); } // Potentially ambiguous method. static void myPrint() { Console.WriteLine("Not a member of csharp_station.tutorial.myExample."); } } // C# Station Tutorial Namespace namespace csharp_station.tutorial { class myExample { public static void myPrint() { Console.WriteLine("This is a member of csharp_station. tutorial.myExample."); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
27 MI KE
TM approved
Version 2005/2
unique types that allow you to assign symbolic names to integral values.
that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value
Along the same lines, integral types and enums are not
implicitly interchangable.
All assignments between different enum types and integral
types require an explicit cast.
because they are symbolic, allowing you to work with integral values, but using a meaningful name to do so.
For example, what type of code would you rather work with -
a set of values named North, South, East, and West or the set
respectively.
Enums make working with strongly typed constants via
symbolic names easy.
28 MI KE
TM approved
Version 2005/2
assignment copies the value of one enum to another.
with both lower case, enum , and upper case, Enum .
that the C# type, enum, inherits the Base Class Library (BCL) type, Enum. Use the C# type, enum, to define new enums and use the BCL type, Enum, to implement static enum methods.
set of related numbers in a program, consider replacing those numbers with enums. It will make a program more readable and type safe.
29 MI KE
TM approved
Version 2005/2
public enum Volume { Low, Medium, High } class EnumSwitch { static void Main() { Volume myVolume = Volume.Medium; switch (myVolume) { case Volume.Low : Console.WriteLine("The volume has been turned Down."); break; case Volume.Medium : Console.WriteLine("The volume is in the middle."); break; case Volume.High : Console.WriteLine("The volume has been turned up."); break; } Console.ReadLine(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
30 MI KE
TM approved
Version 2005/2
identifier (Volume), and contains a comma separated list of values enclosed within curly braces.
myVolume variable in the Main method. Since an enum is a value type, we can assign a value (Volume.Medium) to it directly, similar to the simple types such as int or double. Once the myVolume variable is declared and initialized, it is used in the switch statement. Each of the case statements represent a unique member of the Volume enum.
qualified with the "Volume" identifier to guarantee type
then Meat.Medium would definitely have different semantics than Volume.Medium. With both enums in scope, it would be ambiguous to just use the Medium identifier without type
are not made.
31 MI KE
TM approved
Version 2005/2
using System; // declares the enum public enum Volume : byte { Low = 1, Medium, High } class EnumBaseAndMembers { static void Main() { // create and initialize // instance of enum type Volume myVolume = Volume.Low; // make decision based // on enum value switch (myVolume) { case Volume.Low: Console.WriteLine("The volume has been turned Down."); break; case Volume.Medium: Console.WriteLine("The volume is in the middle."); break; case Volume.High: Console.WriteLine("The volume has been turned up."); break; } Console.ReadLine(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
32 MI KE
TM approved
Version 2005/2
syntax following the enum identifier, Volume. This ensures that the Volume enum may only have members with values that are valid for type byte.
value changed to 1. The same syntax, < member> = <value>, may be applied to any member of the
references, circular references, and duplicate references in enum members.
Medium=1, and High=2 because the first member of an enum defaults to 0 and the following members default to one more than their predecessor. However, here the Volume enum has its Low member set to 1, which means that Medium=2 and High=3.
33 MI KE
TM approved
Version 2005/2
using System; struct Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } public Point Add(Point pt) { Point newPt; newPt.x = x + pt.x; newPt.y = y + pt.y; return newPt; } } /// Example of declaring and using a struct class StructExample { static void Main(string[] args) { Point pt1 = new Point(1, 1); Point pt2 = new Point(2, 2); Point pt3; pt3 = pt1.Add(pt2); Console.WriteLine("pt3: { 0} :{ 1} ", pt3.x, pt3.y); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
class, but with differences.
initializes its fields to the x and y values passed in.
will accept another Point struct, add it to this struct, and return a new struct.
34 MI KE
TM approved
Version 2005/2
It does not need to be instantiated with a new operator, like a
class.
When this occurs, the struct is implicitly instantiated with its default
(or parameterless) constructor.
The parameterless constructor initializes all struct fields to default
false.
It's illegal to define a parameterless constructor for a struct.
In the previous listing, the pt1 and pt2 Point structs are initialized
with values by using the constructor defined in the Point struct.
A third Point struct, pt3 is declared and defaults to using the
parameterless (default) constructor, because it doesn't matter what it's value is at this point.
The Add() method of the pt1 struct is then invoked, passing the pt2
struct as a parameter. The result is assigned to pt3, showing that a struct may be used just like any other value type.
35 MI KE
TM approved
Version 2005/2
programs.
handle program errors in our code.
For example, validating user input, checking for null
are what we expect, are all examples of good standard error handling that we should be doing all the time.
error will occur.
For example, we can't predict when we'll receive a file I/ O
error, run out of system memory, or encounter a database error.
These things are generally unlikely, but they could still
happen and we want to be able to deal with them when they do occur. This is where exception handling comes in.
36 MI KE
TM approved
Version 2005/2
When exceptions occur, they are said to be
"thrown".
What is actually thrown is an object that is derived
from the System.Exception class.
The thrown exceptions are handled with try/catch
blocks.
The System.Exception class provides several
methods and properties for obtaining information on what went wrong. For example,
the Message property provides summary information
about what the error was,
the StackTrace property provides information from the
stack for where the problem occurred, and
the ToString() method is overridden to reveal a
verbose description of the entire exception.
37 MI KE
TM approved
Version 2005/2
Identifying the exceptions we'll need to handle
depends on the routine we're writing.
For example, if the routine opened a file with the
System.IO.File.OpenRead() method, it could throw any of the following exceptions:
SecurityException ArgumentException ArgumentNullException PathTooLongException DirectoryNotFoundException UnauthorizedAccessException FileNotFoundException NotSupportedException
38 MI KE
TM approved
Version 2005/2
When exceptions are thrown, you need to be able to
handle them by implementing a try/catch block.
Code that could throw an exception is put in the try block
an exception handling code goes in the catch block.
using System; using System.IO; class TryCatchDemo { static void Main(string[] args) { try { File.OpenRead("NonExistentFile"); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } } 1 2 3 4 5 6 7 8 9 10 11 12 Although the code
in the this Listing
catch block, all exceptions will be caught there because the type is
exception type "Exception".
39 MI KE
TM approved
Version 2005/2
before their more general parent exceptions.
multiple catch blocks:
If the file doesn't exist, a FileNotFoundException exception will be
thrown and caught by the first catch block.
However, if a PathTooLongException exception was raised, the
second catch part would catch the exception. This is because there isn't a catch block for the PathTooLongException exception and the generic Exception type catch block is the only option available to catch the exception.
catch(FileNotFoundException fnfex) { Console.WriteLine(fnfex.ToString()); } catch(Exception ex) { Console.WriteLine(ex.ToString()); }
40 MI KE
TM approved
Version 2005/2
An exception can leave your program in an
A catch block is a good place to figure out what
Sometimes you need to perform clean up
41 MI KE
TM approved
Version 2005/2
using System; using System.IO; class FinallyDemo { static void Main(string[] args) { FileStream outStream = null; FileStream inStream = null; try {
"DestinationFile.txt"); inStream = File.OpenRead( "BogusInputFile.txt"); } catch(Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (outStream != null) {
Console.WriteLine( "outStream closed."); } if (inStream != null) { inStream.Close(); Console.WriteLine( "inStream closed."); } } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
42 MI KE
TM approved
Version 2005/2
The previous listing illustrates the usefulness of a finally
block.
As we know, a file stream must be closed when your done
with it. In this case, the file stream is the resource that needs to be cleaned up.
now has a handle to an open file resource.
When trying to open the inStream, a FileNotFoundException
exception is raised, causing control to go immediately to the catch block.
It's possible to close the outStream in the catch block, but
what if the algorithm executed successfully without an exception? On success, the file would never be closed.
Fortunately, we've included a finally block, which will
always be executed. That's right, regardless of whether the algorithm in the try block raises an exception or not, the code in the finally block will be executed before control leaves the method.
43 MI KE
TM approved
Version 2005/2
A finally block is not required and you may ask what
happens if you just put code after the catch block.
True, under normal circumstances, if the exception is
caught, all code following the catch will be executed.
However, try/ catch/ finally is for exceptional circumstances
and it is better to plan for the worst to make our program more robust.
For example, if one of the catch handlers re-threw and
exception or caused another exception, the code following the catch block (not in a finally block) would never be executed.
Also, if we don't catch the exception at all, program flow
would immediately do a stack walk looking for an exception handler that fits and the code following the catch blocks would not be executed.
Since there is too much potential for code in an algorithm to
not be executed, a finally block is our insurance for executing those critical actions we need.