Vous êtes sur la page 1sur 18

C# 30

Arrays and Strings 1

C# 3.0
Chapter 7 Arrays and Strings

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

C# 30

Arrays and Strings 2

In This Chapter
Chapter
Declaring and Using Arra
Arrays
s
Multi
Multi-Dimensional
Dimensional Arrays
Copying, Casting and Enumerating Arrays
System.Array Members
Declaring
D l i and
dU
Using
i St
Strings
i
String Equality and Immutability
StringBuilder
Verbatim Strings
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 3

Introduction
The .NET
NET Frame
Framework
ork Class Librar
Library
y
y)
contains an arrayy class ((System.Array)
and a string class (System.String)
These are not just primitive types!

These classes provide rich functionality to


simplify and enhance the manipulation of
these commonly used types

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

C# 30

Arrays and Strings 4

Arrays

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

C# 30

Arrays and Strings 5

Arrays: Introduction
A C# arra
array is a collection of elements of
yp accessible by
y index
the same type
The C# array provides more services than
the C++ array:
Additional methods except standard element access
Range
R
checking
h ki on element
l
access

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

C# 30

Arrays and Strings 6

Array Definition and Usage


int[]intArr;
[]
;
intArr =newint[4];
Rectangle[]rectArray
R
t
l []
tA
=newRectangle[2];

R t
l [2]
string[]namesArr =newstring[2];

Array elements are initialized to their


default initialization values:
Value types types are set to 0 (or its equivalent),
reference ttypes
pes are set to null
n ll

Arrayy elements can be used:


namesArr[0]="John";
namesArr[1]="Mary";
namesArr[1]=
Mary ;
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 7

Arrays Definition and Usage


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

Typical pattern for array access:


for(inti=0;i<namesArr.Length;++i)
Console.WriteLine(namesArr[i]);
C
l W it Li (
A [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

C# 30

Arrays and Strings 8

Arrays Are Reference Types


An array
arra declaration only
onl creates a
y object
j
on the stack
reference to an array
The array itself is created on the managed
g the new operator
heap, using

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

C# 30

Arrays and Strings 9

Multi-Dimensional Arrays
A rectangular array is a multi
multidimensional array

Note:
GetLength()
should be called
outside the loop
(performance!))
(p

All rows have the same length

//Creatingamatrixobject
int [,]matrix=newint [3,3];
for(int i =0;i <matrix.GetLength(0);++i)
f (i t j=0;j<matrix.GetLength(1);++j)
for(int
j 0 j t i G tL
th(1) j)
matrix[i,j]=i*j;
//Printingthematrix
for(int i =0;i <matrix.GetLength(0);++i){
f (i t j=0;j<matrix.GetLength(1);++j)
for(int
j 0 j t i G tL
th(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

C# 30

Arrays and Strings 10

Jagged Arrays
Another type of a multi-dimensional
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=newstring[4][];
employees[0]=newstring[2]{"John","Mary"};
employees[1]=newstring[3]{"Robert","Mike","Sally"};
employees[2]=newstring[4]{"Jane"
employees[2]=newstring[4]{
Jane ,
"Sara"
Sara ,
"John
John ...};
};
employees[3]=newstring[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");
Console.Write(employees[i][j]+
\t );
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 11

The System.Array
System Array Class
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 object
System.Array directly derives from System.Object

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

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

C# 30

Arrays and Strings 12

System Array Members


System.Array
Length
The total number of elements in all dimensions

Rank
The array
arrays
s rank (number of dimensions)

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

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

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

C# 30

Arrays and Strings 13

System Array Members


System.Array
CreateInstance (static)
Creates a new array with an element type, rank and
lower bound (non zero-based
zero based is possible!)

GetLength
Number of elements in the specified dimension

IndexOf / LastIndexOf (static)


The index of the first / last occurrence in a 1-dim array

Reverse(static)
( t ti )
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

C# 30

Arrays and Strings 14

Array Members Usage Example


//Getmatrixarrayproperties:
//
y p p
int k=matrix.Length;
k=matrix.Rank;
k t i G tL
k=matrix.GetLength
th (0);
(0)
k=matrix.GetLength (1);
//Manipulatinganintegersarray:
int[]iarr1={1,2,3,4,5};
i t pos=Array.BinarySearch(iarr1,4);
int
A
Bi
S
h(i
1 4)
Array.Reverse(iarr1,0,iarr1.Length);
Array.Clear(iarr1,0,iarr1.Length);
y
(
, ,
g );
//Creatinganarraydynamically:
A
i tA
A
C
t I t
(t
f(i t) 3)
ArrayintArray
=Array.CreateInstance(typeof(int),3);
intArray.SetValue(100,0);
intArray.SetValue(101,1);
y
(
, );
intArray.SetValue(102,2);
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 15

Casting Arrays
Only reference type arrays can be directly
cast (if a conversion exists):
rectArray[0]=newRectangle(5,5,10,10);
rectArray[1]=newRectangle(10,10,20,20);
object[]objArray
bj t[] bjA
=rectArray;

tA

yp arrays
y must be copied
p
Value type
with
Array.Copy():
int[]intArray
i
t[]i tA
={1,2,3};
{1 2 3}
double[]doubleArray =newdouble[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

C# 30

Arrays and Strings 16

The foreach Statement


The C# arra
array pro
provides
ides another way
a to
iterate over its elements using
g the
foreach statement
foreach (int i iniarr2)
Console.WriteLine(i);

The foreach statement cant be used to modify the


array contents
If the array contains references, the referenced
objects
j
can be modified

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

C# 30

Arrays and Strings 17

Array Range Checking


Arra
Arrays
s perform range
range-checking
checking on e
every
er
element access
An out-of-bounds index causes an
g
p
IndexOutOfRangeException
This ensures that memory corruption does not ensue,
and that protected memory is not accidentally read

Exceptions
E
i
will
ill b
be di
discussed
d iin d
detailil llater

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

C# 30

Arrays and Strings 18

Arrays Last Remarks


.NET
NET arrays
arra s are zero
ero based b
butt
y
() allows
Array.CreateInstance()
creating arrays with different lower bounds
Only zero-based
zero based arrays are CLS
CLS-compliant
compliant
Zero-based arrays provide the best performance

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

C# 30

Arrays and Strings 19

S i
Strings

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

C# 30

Arrays and Strings 20

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

string represents an immutable string of


Unicode characters
A .NET character is two bytes long

St
Strings
i
are assigned
i
d with
ith a lit
literall syntax:
t
stringhello="HelloWorld!";
g
;
stringbye;
bye="GoodBye";

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

C# 30

Arrays and Strings 21

String Members
Empty
A static read-only field representing the empty string

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

Compare
Compares
C
b t
between
two
t
specified
ifi d String
St i
objects
bj t
Implemented by the == operator as well
Has an equivalent instance method CompareTo()
()

Concat
Concatenates one or more strings
byy the + operator
as well
Implemented
p
p
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 22

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

Equals
q
Determines whether two strings have the same value
Has an equivalent
q
instance method EqualsTo()
q
()

Format
Used to format a String ({0} notation)

Equality Operator (==)


Determines whether two strings have the same value
The corresponding
(!=)
p
g Inequality
q
y Operator
p
( ) is also
defined
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 23

String Members
Indexer []
Gets the character at a an index

Length
Gets the number of characters in the string

EndsWith / StartsWith
D
Determines
t
i
whether
h th th
the string
t i ends
d / starts
t t with
ith a
substring

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

Insert
Inserts a new string into the existing string
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 24

String Members
PadLeft / PadRight
Right- or left-aligns the string with a character

Remove
Deletes a specified number of characters

Replace
Replaces
R l
a substring
b t i or character
h
t with
ith another
th

ToLower / ToUpper
pp
Returns a copy of the string in lowercase / uppercase

Trim
Removes characters from the beginning / end
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 25

String Usage Example


stringstr1="Hello";
stringstr1=
Hello ;
stringstr2="World!";
stringconcatHello =str1+str2;
stringgreeting="HappyBirthday";
stringnewGreeting =
greeting.Replace("Birthday","NewYear!!!");
if(greeting.EndsWith("Birthday"))
position=greeting.IndexOf("Birthday");
if(greeting==newGreeting){
Console.WriteLine("Dowehaveonlyonegreeting?");
}else{
Console.WriteLine(
"HappyBirthdayANDHappyNewYear!);
HappyBirthdayANDHappyNewYear! );
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 26

String Equality Is By Value


string is a reference type,
t pe but
b t strings are
byy value and not byy reference:
compared
p
stringstr1="Hello";
stringstr2="World!";
t i t 2 "W ld!"
stringconcatHello =str1+str2;
stringhello="HelloWorld!";
if(hello==
if(h
ll
concatHello)//true
tH ll )//t
Console.WriteLine ("Stringsvaluesareequal!");
if(Object.ReferenceEquals(hello,concatHello))//false
Console.WriteLine("Stringsreferencesareequal?");
else//true
l //t
Console.WriteLine("Stringsreferencesaredifferent!");
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 27

Strings Are Immutable


C# strings are immutable
immutable, which means
they cannot be changed
Mutating methods do not change the instance they
return a new one
stringoriginal="happybirthday";
stringfix1=original.Replace("birthday","NewYear");
stringfix2=fix1.Replace('h','H');
i
fi
fi
l
('h' ' ')
stringfix3=fix2.Insert(enhancedGreeting2.Length,"!!!");
Console.WriteLine(original);
Console.WriteLine(fix1);
Console.WriteLine(fix2);
l
i
i (fi )
Console.WriteLine(fix3);

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

C# 30

Arrays and Strings 28

Strings Are Immutable


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

This is expensive!
Concatenating a single character 1,000 times means
1 000 copies of the string are created!
1,000
Total memory wasted: 999
n = 499500
n =1

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

C# 30

Arrays and Strings 29

The StringBuilder Class


Sometimes its desirable to modify
modif a string
System.Text.StringBuilder class
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

C# 30

Arrays and Strings 30

StringBuilder Members
StringBuilder Constructor
Accepts various types (e.g., string, characters array)
as 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

Length
Gets the number of characters in this instance

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

C# 30

Arrays and Strings 31

StringBuilder Members
Append
Appends a string to the end of the instance

Insert
Inserts a string somewhere in the instance

Remove
Removes
R
a substring
b t i or character
h
t sett

Replace
p
Replaces a substring or a character with another
string or character

ToString
Converts a StringBuilder to a string
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 32

StringBuilder Usage
usingSystem.Text;
StringBuilder
greeting=newStringBuilder(original);
St i B ild
ti
St i B ild ( i i l)
greeting.Replace("birthday","NewYear");
g
greeting.Replace('h','H',1,1);
g
p
(
,
, , );
greeting.Append("!!!");
Console.WriteLine(greeting);
C
l W it Li (
ti )
//orgreeting.ToString()

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

C# 30

Arrays and Strings 33

String Literals
C# supports two forms of string literals:
regular string literals and verbatim
string
t i literals
lit
l
Regular
g
string
g literals ((enclosed in )) can contain
escape sequences
\t for the tab character, \n for new line, \\ for backslash
((and
d th
there are more))
stringpath="c:\\dvp\\strings\\string.cs";
stringpath=
c:\\dvp\\strings\\string.cs ;
stringregularWithTab ="Hello\tWorld";

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

C# 30

Arrays and Strings 34

Verbatim Strings
Verbatim literals are preceded with @
Escape sequences are not processed
stringpathVerbatim =@"c:\dvp\strings\string.cs";
stringregularWithTab
g
g
="Hello\tWorld";
;
//ThelatterstringisHello\tWorld

The
Th @ sign
i can also
l be
b used
d to
t give
i 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

C# 30

Arrays and Strings 35

Summary
Declaring and Using Arra
Arrays
s
Multi
Multi-Dimensional
Dimensional Arrays
Copying, Casting and Enumerating Arrays
System.Array Members
Declaring
D l i and
dU
Using
i St
Strings
i
String Equality and Immutability
StringBuilder
Verbatim Strings
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Arrays and Strings 36

Arrays and Strings

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

Vous aimerez peut-être aussi