5-arrays-datastructures

Arrays & Strings
& other collections
Arrays
 Arrays are data structures consisting of related data items of the
same type.
 Arrays are fixed-length entities—they remain the same length once
they are created.
 Length property gives the length of the array.
 static Array.Resize resizes an array. It takes two arguments—the
array to be resized and the new length.
 Arrays are reference types—what we typically think of as an array is
actually a reference to an array object.
 If you pass an array parameter to a method, it is passed by reference.
 The elements of an array can be either value types or reference
types.
 For example, every element of an int array is an int value, and every
element of a string array is a reference to a string object.
 We access an array element specifying array’s name and element’s
index (position in the array).
 Index starts at 0 (zero).
 CLR performs bounds checking for you and throws
IndexOutOfRangeException.
Examples

See Arrays

int[] c = new int[12];
string[] c = new string[10];

int[] c;
c = new int[12];

int[] array = {32, 27, 64, 18, 95, 14, 90, 70,
60, 37};
 for (int i = 0; i < array.Length; i++)
Console.WriteLine("{0} {1}", i, array[i]);
 const int ARRAY_LENGTH = 10;
int[] array = new int[ARRAY_LENGTH];
for (int i = 0; i < array.Length; i++)
array[i] = 2 + 2 * i;
foreach
 The foreach statement iterates through the elements of an
entire array or collection.
foreach (type identifier in arrayName )
{
<statement1>;
...
<statementN>;
}
 type and identifier are the type and name (e.g. int number) of
the iteration variable.
 The type of the iteration variable must match the type of the
elements in the array.
 The iteration variable represents successive values in the array on
successive iterations of the foreach statement.
Example: foreach
int[] array = {87, 68, 94, 100, 83, 78, 85, 91, 76};
int total = 0;
// add each element's value to total
foreach ( int number in array )
total += number;
 The foreach statement can be used with any collection .NET provides as
long as the type implements the IEnumerable and IEnumerator
interface.
Implicitly Typed Variables
 C# provides a new feature—called implicitly typed local
variables—that enables the compiler to infer a local variable’s
type based on the type of the variable’s initializer.
 To distinguish such an initialization from a simple assignment
statement, the var keyword is used in place of the variable’s
type.
 You can use local type inference with control variables in the
header of a for or foreach statement.
 if myArray is an array of ints, the following foreach statement
headers are equivalent:
foreach (int number in myArray)
foreach (var number in myArray)
Multidimensional Arrays
 2-dimensional rectangular array:
 An array with m rows and n columns is called an m-by-n array.
 Every element in array a is identified by an array-access expression of the
form a[ row, column ];
 A two-by-two rectangular array b can be declared and initialized as follows:
int[ , ] b = { { 1, 2 }, { 3, 4 } };
 The initializer values are grouped by row in braces.
System.String
 string is the alias for System.String
 A string is an object of class string in the System




namespace representing a series of characters.
These characters can be uppercase letters, lowercase
letters, digits and various special characters.
Character constants are established according to the
Unicode character set.
String is a reference type.
The keyword null represents a null, not an empty string
(which is a string object that is of length 0 and contains no
characters). The string.Empty should be used if you
need a string with no characters.
StringConstructor.cs
• Class string provides 8 constructors. Below is the use of 3 constructors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Fig. 18.1: StringConstructor.cs
// Demonstrating string class constructors.
using System;
Assign a string literal to
string reference
originalString.
class StringConstructor
{
public static void Main( string[] args )
{
// string initialization
char[] characterArray =
{ 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' };
string originalString = "Welcome to C# programming!";
string string1 = originalString;
string string2 = new string( characterArray );
string string3 = new string( characterArray, 6, 3 );
string string4 = new string( 'C', 5 );
Copy a reference
to another
string literal.
The string constructor
can take a character array
as an argument.
The string constructor
can take a char array and
two int arguments for
starting position and
length.
The string constructor can
take as arguments a character
and an int specifying the
number of times to repeat that
character in the string.
String Properties
• Property Length allows you to determine the number of
characters in a string.
• The string indexer treats a string as an array of chars and
returns each character at a specific position in the string.
• As with arrays, the first element of a string is considered to
be at position 0.
• Attempting to access a character that is outside a string’s bounds
i.e., an index less than 0 or an index greater than or equal to the
string’s length) results in an IndexOutOfRangeException.
• The string method CopyTo copies a specified number of
characters from a string into a char array.
• StringMethods.cs
Comparing Strings
 Method Equals tests any two objects for equality (i.e., checks




whether the objects contain identical contents).
The string class’s Equals method uses a lexicographical
comparison—comparing the integer Unicode values of
character in each string.
The overloaded string equality operator == also uses a
lexicographical comparison to compare two strings.
String comparisons are case-sensitive.
Method CompareTo returns:
 0 if the strings are equal
 A negative value if the calling string is less than the argument string
 A positive value if the calling string is greater than the argument.
 Example: StringCompare.cs
Searching Strings
 StringIndexMethods.cs
 StartWith and EndWith
string s = “started”;
if ( s.StartsWith(“st”) )
…
if ( s.EndsWith(“ed”) )
…
 IndexOf
 locates the first occurrence of a character or substring in a string and
returns its index, or -1 if it is not found.
 LastIndexOf
 like IndexOf, but searches from the end of the string.
 IndexOfAny and LastIndexOfAny
 take an array of characters as the first argument and return the index of
the first occurrence of any of the characters in the array.
Substring and Concat
 Substring methods which create a new string by copying
part of an existing string.
s.Substr(20);
s.Substr(0, 6);
 Like the + operator, the static method Concat of class
string concatenates two strings and returns a new string.
string strNew = String.Concat(str1, str2);
String strNew = str1 + str2;
 string2 = string1.Replace(‘e’, ‘E’);
 string2 = string1.ToUpper() and
string2 = string1.ToLower()
 string2 = string1.Trim();
 Examples: StringMethods2.cs
char Methods
 char is an alias for the struct Char.
 StaticCharMethodsForm.cs
 Char method IsDigit determines whether a character





is defined as a digit.
IsLetter determines whether a character is a letter.
IsLetterOrDigit determines whether a character is a
letter or a digit.
IsLower determines whether a character is a lowercase
letter.
IsUpper determines whether a character is an uppercase
letter.
ToUpper returns a character’s uppercase equivalent, or
the original argument if there is no uppercase equivalent.
char Methods
 ToLower returns a character lowercase equivalent, or the




original argument if there is no lowercase equivalent.
IsPunctuation determines whether a character is a
punctuation mark, such as "!", ":" or ")".
IsSymbol determines whether a character is a symbol,
such as "+", "=" or "^".
Static method IsWhiteSpace.
Public instance methods: ToString, Equals, and
CompareTo.
Common Data Structures - summary
 We’ve seen Array only so far  fixed-size (can grow with





Resize)
Dynamic data structures can automatically grow and shrink
at execution time.
Linked lists are collections of data items that are “chained
together”.
Stacks have insertions and deletions made at only
one end: the top.
Queues represent waiting lines; insertions are made
at the back and deletions are made from the front.
Binary trees facilitate high-speed searching and sorting of
data.
Collections
 For the vast majority of applications, there is no need to




build custom data structures.
Instead, you can use the prepackaged data-structure
classes provided by the .NET Framework.
These classes are known as collection classes—they store
collections of data. Each instance of one of these classes is
a collection of items.
Collection classes enable programmers to store sets of
items by using existing data structures, without concern for
how they are implemented.
System.Collections contains collections that store
references to objects.
ArrayList
 The ArrayList collection class is a conventional arrays and
provides dynamic resizing of the collection.
Method / Property
Add
Capacity
Clear
Contains
Count
IndexOf
Description
Adds an object to the end of the ArrayList.
Property that gets and sets the number of elements for which space
is currently reserved in the ArrayList.
Removes all elements from the ArrayList.
Determines whether an element is in the ArrayList.
Read-only property that gets the number of elements stored in the
ArrayList.
Returns the zero-based index of the first occurrence of a value in the
ArrayList
Insert
Inserts an element into the ArrayList at the specified index.
Remove
Removes the first occurrence of a specific object from the ArrayList.
RemoveAt
TrimToSize
Removes the element at the specified index of the ArrayList.
Sets the capacity to the actual number of elements in the ArrayList.
ArrayList
 Let’s write code to use ArrayList.
 Suppose we have two color string arrays as follows:
private static readonly string[] colors =
{ "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" };
private static readonly string[] removeColors =
{ "RED", "WHITE", "BLUE" };
1.
2.
3.
4.
5.
Let’s create an arrayList and add items in colors into it.
Let’s display the size and capacity of arrayList.
Let’s find the index of the item “BLUE”.
Let’s write a method that removes the items in one
ArrayList from another. And then call that method to
remove removeColors array from our first arrayList.
ArrayListTest.cs
HashTable
 Arrays uses nonnegative integer indexes as keys. Sometimes
associating these integer keys with objects to store them is
impractical, so we develop a scheme for using arbitrary keys.
 When an application needs to store something, the scheme
could convert the application key rapidly to an index.
 Once the application has a key for which it wants to retrieve
the data, simply apply the conversion to the key to find the
array index where the data resides.
 The scheme we describe here is the basis of a technique
called hashing, in which we store data in a data structure
called a hash table.
HashTable
 A hash function performs a calculation that determines




where to place data in the hash table.
The hash function is applied to the key in a key/value pair
of objects.
Class Hashtable can accept any object as a key. For this
reason, class object defines method GetHashCode,
which all objects inherit.
Example: Let’s write a program that counts the number of
occurrences of each word in a string read from console.
To split the sentence into words, we will use this:
// split input text into tokens
string[] words = Regex.Split( input, @"\s+" );
 HashTable solution.
HashTable
 Hashtable method ContainsKey determines whether a key is in the
hash table.
 Read-only property Keys returns an ICollection that contains all
the keys.
 Hashtable property Count returns the number of key/value pairs in the
Hashtable.
 If you use a foreach statement with a Hashtable object, the iteration
variable will be of type DictionaryEntry.
 The enumerator of a Hashtable (or any other class that implements
IDictionary) uses the DictionaryEntry structure to store key/value pairs.
 This structure provides properties Key and Value for retrieving the key
and value of the current element.
 If you do not need the key, class Hashtable also provides a read-only
Values property that gets an ICollection of all the values stored in
the Hashtable.
Stack & Queue
 Stack:
 Push
 Pop
 Peek
 Example:
 StackTest.cs
 Queue:
 Enqueue
 Dequeue
 Peek
 QueueTest.cs