18
Arrays and Strings 1 C# 30 C# 3.0 C# 3.0 Chapter 7 – Arrays and Strings © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel In This Chapter Arrays and Strings 2 C# 30 In This ChapterDeclaring and Using Arra s Declaring and Using Arrays Multi-Dimensional Arrays Multi Dimensional Arrays Copying, Casting and Enumerating Arrays System.Array Members D l i dUi St i Declaring and Using Strings String Equality and Immutability String Equality and Immutability StringBuilder Verbatim Strings © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Chapter 7 - Arrays and Strings

Embed Size (px)

DESCRIPTION

f

Citation preview

Page 1: Chapter 7 - Arrays and Strings

Arrays and Strings 1C# 30

C# 3.0C# 3.0

Chapter 7 – Arrays and Strings

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

In This ChapterArrays and Strings 2C# 30

In This Chapter…

Declaring and Using Arra s• Declaring and Using Arrays

• Multi-Dimensional ArraysMulti Dimensional Arrays

• Copying, Casting and Enumerating Arrays

• System.Array Members

D l i d U i St i• Declaring and Using Strings

• String Equality and Immutability• String Equality and Immutability

• StringBuilder

• Verbatim Strings

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 2: Chapter 7 - Arrays and Strings

IntroductionArrays and Strings 3C# 30

Introduction

The NET Frame ork Class Librar• The .NET Framework Class Library contains an array class (System.Array) y ( y y)and a string class (System.String)

These are not just primitive types!– These are not just primitive types!

• These classes provide rich functionality to simplify and enhance the manipulation ofsimplify and enhance the manipulation of these commonly used types

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Arrays and Strings 4C# 30

AArrays

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 3: Chapter 7 - Arrays and Strings

Arrays: IntroductionArrays and Strings 5C# 30

Arrays: Introduction

A C# arra is a collection of elements of• A C# array is a collection of elements of the same type accessible by indexyp y

• The C# array provides more services than the C++ array:the C++ array:– Additional methods except standard element access

R h ki l– Range checking on element access

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Array Definition and UsageArrays and Strings 6C# 30

Array Definition and Usageint[] intArr;[] ;intArr = new int[4];

R t l []  tA    R t l [2]Rectangle[] rectArray = new Rectangle[2];string[] namesArr = new string[2];

• Array elements are initialized to their default initialization values:default initialization values:– Value types types are set to 0 (or its equivalent),

reference t pes are set to n llreference types are set to null

• Array elements can be used:ynamesArr[0] = "John";namesArr[1] = "Mary";

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

namesArr[1] =  Mary ;

Page 4: Chapter 7 - Arrays and Strings

Arrays Definition and UsageArrays and Strings 7C# 30

Arrays Definition and Usage

Arra s can be initiali ed on creation• Arrays can be initialized on creation:string[] namesArr2 = new string [2] {"John", "Mary"};

• Typical pattern for array access:

string[] namesArr3 = {"John", "Mary"};

• Typical pattern for array access:for (int i = 0; i < namesArr.Length; ++i)

C l W it Li  ( A [i])

• Where did the Length property come

Console.WriteLine (namesArr[i]);

Where did the Length property come from?– The System.Array base class

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Arrays Are Reference TypesArrays and Strings 8C# 30

Arrays Are Reference Types

An arra declaration onl creates a• An array declaration only creates a reference to an array object on the stacky j

The array itself is created on the managed• The array itself is created on the managed heap, using the new operatorg

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 5: Chapter 7 - Arrays and Strings

Multi-Dimensional ArraysArrays and Strings 9C# 30

Multi-Dimensional Arrays

• A rectangular array is a multi• A rectangular array is a multi-dimensional array Note:

GetLength()– All rows have the same length

// Creating a matrix object

GetLength() should be called outside the loop (performance!)// Creating a matrix object

int [,] matrix = new int [3,3];for (int i = 0; i < matrix.GetLength(0); ++i)

f  (i t j   0  j    t i G tL th(1)   j)

(p )

for (int j = 0; j < matrix.GetLength(1); ++j)matrix [i,j] = i*j;

// Printing the matrixfor (int i = 0; i < matrix.GetLength(0); ++i) {

f  (i t j   0  j    t i G tL th(1)   j)for (int j = 0; j < matrix.GetLength(1); ++j)Console.Write (matrix[i,j] + "\t");

Console.WriteLine();

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Console.WriteLine();}

Jagged ArraysArrays and Strings 10C# 30

Jagged Arrays

• Another type of a multi dimensional array• Another type of a multi-dimensional array is the jagged array– A jagged array is actually an array of arrays, where

each of the inner arrays may have a different length

string[][] employees = new string[4][];

employees[0] = new string[2]{"John", "Mary"};employees[1] = new string[3]{"Robert", "Mike", "Sally"};employees[2] = new string[4]{"Jane"  "Sara"  "John“ };employees[2] = new string[4]{ Jane ,  Sara ,  John ...};employees[3] = new string[5]{"Jack", "Don", "Roy“...};

for (int i = 0; i < employees.Length; ++i)for (int j = 0; j < employees[i].Length; ++j)

Console Write(employees[i][j] + "\t");

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Console.Write(employees[i][j] +  \t );

Page 6: Chapter 7 - Arrays and Strings

The System Array ClassArrays and Strings 11C# 30

The System.Array Class

• C# arrays provide richer functionality than• C# arrays provide richer functionality than their C++ equivalents– The main source for these additional methods is the

class System.Array, which is the base class of any C# array objectC# array object

– System.Array directly derives from System.Object

• System Array contains several properties• System.Array contains several properties and methods that are very useful for array manipulationmanipulation

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

System Array MembersArrays and Strings 12C# 30

System.Array Members

• Length• Length– The total number of elements in all dimensions

• Rank– The array’s rank (number of dimensions)The array s rank (number of dimensions)

• BinarySearch (static)Bi h di i l t d– Binary-searches a one-dimensional sorted array

• Clear (static)( )– Sets array elements to zero or to a null reference

• Copy (static)• Copy (static)– Copies a section of one array to another array

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 7: Chapter 7 - Arrays and Strings

System Array MembersArrays and Strings 13C# 30

System.Array Members

• CreateInstance (static)• CreateInstance (static)– Creates a new array with an element type, rank and

lower bound (non zero based is possible!)lower bound (non zero-based is possible!)

• GetLength– Number of elements in the specified dimension

• IndexOf / LastIndexOf (static)IndexOf / LastIndexOf (static)– The index of the first / last occurrence in a 1-dim array

( t ti )• Reverse(static)– Reverses the order of the elements

• Sort(static)Sorts the elements

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

– Sorts the elements

Array Members Usage ExampleArrays and Strings 14C# 30

Array Members Usage Example// Get matrix array properties:// y p pint k = matrix.Length;k = matrix.Rank;k    t i G tL th (0)k = matrix.GetLength (0);k = matrix.GetLength (1);

// Manipulating an integers array:int[] iarr1 = {1,2,3,4,5}; i t    A Bi S h(i 1  4)int pos = Array.BinarySearch(iarr1, 4);Array.Reverse(iarr1, 0, iarr1.Length); Array.Clear(iarr1, 0, iarr1.Length);y ( , , g );

// Creating an array dynamically:A  i tA  A C t I t (t f(i t)  3)Array intArray = Array.CreateInstance(typeof(int), 3);intArray.SetValue(100, 0);intArray.SetValue(101, 1);

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

y ( , );intArray.SetValue(102, 2);

Page 8: Chapter 7 - Arrays and Strings

Casting ArraysArrays and Strings 15C# 30

Casting Arrays

• Only reference type arrays can be directly• Only reference type arrays can be directly cast (if a conversion exists):rectArray[0] = new Rectangle(5,5,10,10);rectArray[1] = new Rectangle(10,10,20,20);bj t[]  bjA   tA

• Value type arrays must be copied with object[] objArray = rectArray;

yp y pArray.Copy():i t[] i tA  { 1  2  3 }int[] intArray = { 1, 2, 3 };double[] doubleArray = new double[intArray.Length];Array.Copy(intArray, doubleArray, 3); y py( y, y, );

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

The foreach StatementArrays and Strings 16C# 30

The foreach Statement

The C# arra pro ides another a to• The C# array provides another way to iterate over its elements using the gforeach statementforeach (int i in iarr2)

Console.WriteLine(i);

– The foreach statement can’t be used to modify the array contents

– If the array contains references, the referenced objects can be modifiedj

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 9: Chapter 7 - Arrays and Strings

Array Range CheckingArrays and Strings 17C# 30

Array Range Checking

Arra s perform range checking on e er• Arrays perform range-checking on every element access– An out-of-bounds index causes an IndexOutOfRangeExceptiong p

– This ensures that memory corruption does not ensue, and that protected memory is not accidentally readand that protected memory is not accidentally read

E i ill b di d i d il l• Exceptions will be discussed in detail later

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Arrays Last RemarksArrays and Strings 18C# 30

Arrays Last Remarks

NET arra s are ero based b t• .NET arrays are zero based but Array.CreateInstance() allows y ()creating arrays with different lower bounds

Only zero based arrays are CLS compliant– Only zero-based arrays are CLS-compliant

– Zero-based arrays provide the best performance

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 10: Chapter 7 - Arrays and Strings

Arrays and Strings 19C# 30

S iStrings

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

StringsArrays and Strings 20C# 30

Strings

• The C# string type is an alias to the• The C# string type is an alias to the .NET System.String– Directly derives from System.Object– string is a reference type

• string represents an immutable string of Unicode charactersUnicode characters– A .NET character is two bytes long

St i i d ith lit l t• Strings are assigned with a literal syntax:string hello = "Hello World!";g ;string bye;bye = "Good Bye";

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 11: Chapter 7 - Arrays and Strings

String MembersArrays and Strings 21C# 30

String Members

• Empty• Empty– A static read-only field representing the empty string

• String Constructor– Has several overloaded versions (e.g. char fill)Has several overloaded versions (e.g. char fill)

• CompareC b t t ifi d St i bj t– Compares between two specified String objects

– Implemented by the == operator as well()– Has an equivalent instance method CompareTo()

• Concat– Concatenates one or more strings

Implemented by the + operator as well

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

p y p

String MembersArrays and Strings 22C# 30

String Members

• Copy• Copy– Creates a clone with the same value as a string– Has an equivalent instance method CopyTo()

• Equalsq– Determines whether two strings have the same value

Has an equivalent instance method EqualsTo()q q ()

• FormatUsed to format a String ({0} notation)– Used to format a String ({0} notation)

• Equality Operator (==)– Determines whether two strings have the same value– The corresponding Inequality Operator (!=) is also

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

p g q y p ( )defined

Page 12: Chapter 7 - Arrays and Strings

String MembersArrays and Strings 23C# 30

String Members

• Indexer []• Indexer []– Gets the character at a an index

• Length– Gets the number of characters in the stringGets the number of characters in the string

• EndsWith / StartsWithD t i h th th t i d / t t ith– Determines whether the string ends / starts with a substring

I d Of / L tI d Of• IndexOf / LastIndexOf– Finds the first / last occurrence of a substring

• InsertInserts a new string into the existing string

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

– Inserts a new string into the existing string

String MembersArrays and Strings 24C# 30

String Members

• PadLeft / PadRight• PadLeft / PadRight– Right- or left-aligns the string with a character

• Remove– Deletes a specified number of charactersDeletes a specified number of characters

• ReplaceR l b t i h t ith th– Replaces a substring or character with another

• ToLower / ToUpperpp– Returns a copy of the string in lowercase / uppercase

• Trim• Trim– Removes characters from the beginning / end

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 13: Chapter 7 - Arrays and Strings

String Usage ExampleArrays and Strings 25C# 30

String Usage Examplestring str1 = "Hello";string str1 =  Hello ;string str2 = " World!";string concatHello = str1+str2;

string greeting = "Happy Birthday";string newGreeting =string newGreeting =

greeting.Replace("Birthday", "New Year!!!");

if (greeting.EndsWith("Birthday"))position = greeting.IndexOf("Birthday");

if (greeting == newGreeting) {Console.WriteLine("Do we have only one greeting?");

} else {Console.WriteLine(

"Happy Birthday AND Happy New Year!”);

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Happy Birthday AND Happy New Year! );}

String Equality Is By ValueArrays and Strings 26C# 30

String Equality Is By Value

string is a reference t pe b t strings are• string is a reference type, but strings are compared by value and not by reference:p y y

string str1 = "Hello";t i   t 2   " W ld!"string str2 = " World!";

string concatHello = str1+str2;

string hello = "Hello World!";

if (h ll   tH ll ) //tif (hello == concatHello) //trueConsole.WriteLine ("Strings values are equal!");

if (Object.ReferenceEquals(hello, concatHello)) // falseConsole.WriteLine("Strings references are equal?");

l   //t

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

else  //trueConsole.WriteLine("Strings references are different!");

Page 14: Chapter 7 - Arrays and Strings

Strings Are ImmutableArrays and Strings 27C# 30

Strings Are Immutable

• C# strings are immutable which means• C# strings are immutable, which means they cannot be changed– Mutating methods do not change the instance – they

return a new one

string original = "happy birthday";string fix1 = original.Replace("birthday", "New Year");

i fi fi l ('h' ' ')string fix2 = fix1.Replace('h', 'H');string fix3 = fix2.Insert(enhancedGreeting2.Length, "!!!");

Console.WriteLine(original);Console.WriteLine(fix1);

l i i (fi )Console.WriteLine(fix2);Console.WriteLine(fix3);

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Strings Are ImmutableArrays and Strings 28C# 30

Strings Are Immutable

• The original string went through three• The original string went through three modifications– Each created a new String instance– The original string is still intact

• This is expensive!This is expensive!– Concatenating a single character 1,000 times means

1 000 copies of the string are created!1,000 copies of the string are created!– Total memory wasted:

499500999

=∑n1∑=n

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 15: Chapter 7 - Arrays and Strings

The StringBuilder ClassArrays and Strings 29C# 30

The StringBuilder Class

Sometimes it’s desirable to modif a string• Sometimes it’s desirable to modify a string

• System.Text.StringBuilder class methods do not return a new instance –methods do not return a new instance –they manipulate an existing one

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

StringBuilder MembersArrays and Strings 30C# 30

StringBuilder Members

• StringBuilder Constructor• StringBuilder Constructor– Accepts various types (e.g., string, characters array)

as well as an initial capacityas well as an initial capacity

• Capacity– Gets or sets the capacity (number of characters the

object can contain without reallocation)

• Indexer– Gets the character at a specified index– Gets the character at a specified index

• Length– Gets the number of characters in this instance

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 16: Chapter 7 - Arrays and Strings

StringBuilder MembersArrays and Strings 31C# 30

StringBuilder Members

• Append• Append– Appends a string to the end of the instance

• Insert– Inserts a string somewhere in the instanceInserts a string somewhere in the instance

• RemoveR b t i h t t– Removes a substring or character set

• Replacep– Replaces a substring or a character with another

string or character

• ToStringConverts a StringBuilder to a string

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

– Converts a StringBuilder to a string

StringBuilder UsageArrays and Strings 32C# 30

StringBuilder Usage

using System.Text;

St i B ild ti      St i B ild ( i i l)StringBuilder greeting = new StringBuilder(original);greeting.Replace("birthday", "New Year");greeting.Replace('h', 'H', 1, 1);g g p ( , , , );greeting.Append("!!!");

C l W it Li ( ti )Console.WriteLine(greeting);//or greeting.ToString()

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 17: Chapter 7 - Arrays and Strings

String LiteralsArrays and Strings 33C# 30

String Literals

• C# supports two forms of string literals:• C# supports two forms of string literals: regular string literals and verbatim

t i lit lstring literals– Regular string literals (enclosed in “”) can contain g g ( )

escape sequences– \t for the tab character, \n for new line, \\ for backslash

( d th )(and there are more)

string path = "c:\\dvp\\strings\\string.cs";string path =  c:\\dvp\\strings\\string.cs ;string regularWithTab = "Hello\tWorld";

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Verbatim StringsArrays and Strings 34C# 30

Verbatim Strings

• Verbatim literals are preceded with @• Verbatim literals are preceded with @– Escape sequences are not processed

string pathVerbatim = @"c:\dvp\strings\string.cs";string regularWithTab = "Hello\tWorld";

Th @ i l b d t i

g g ;//The latter string is Hello\tWorld

• The @ sign can also be used to give an identifier a reserved name:

int @foreach = 17;object @object = null;

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 18: Chapter 7 - Arrays and Strings

SummaryArrays and Strings 35C# 30

Summary

Declaring and Using Arra s• Declaring and Using Arrays

• Multi-Dimensional ArraysMulti Dimensional Arrays

• Copying, Casting and Enumerating Arrays

• System.Array Members

D l i d U i St i• Declaring and Using Strings

• String Equality and Immutability• String Equality and Immutability

• StringBuilder

• Verbatim Strings

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Arrays and Strings 36C# 30

Arrays and Strings

NAME PROCESSING EXERCISEEXERCISE

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel