Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Chapter 2

Array and Strings


Agenda
• Introduction to Arrays
• Defining and using Arrays
• Using foreach for arrays
• Advanced Array
– Dynamic Array
– Multidimensional Arrays
– Jagged Arrays
• Strings
– String Functions

2
Introduction
• A fairly common requirement in writing software is the
need to hold lists of similar or related data.
• You can provide this functionality by using an array.
• Arrays are just lists of data that have a single data type.
• The element of an array are stored together in memory.
• Every element of an array has an index.
• This index can be used to address the element.
– The index of the first element is always 0
– The index of the second element is 1
– The index of the last element is equal to the number
of elements minus 1
3
Defining and using Arrays
• Before an array is used, it is usually declared
<data type> identifier=new <data type>[size];
Example :
– string[ ] strName=new string[20];
– int[ ] n=new int[10];
• To address an element of the array, both the
identifier of the array variable and the index of
the element are needed.
– So, to set the element with index 2 in the array,
you’d do this: strName[2] = “Meseret”;
– To get that same element back again, you’d do this:
MessageBox.Show(strName[2]);

4
Defining and using Arrays…
• It is also possible to define arrays using the values
it will hold by enclosing values in curly brackets and
separating individual values with a comma:
– int [] integers = {1, 2, 3, 4, 5);
– This will create an may of size 5, whose successive
values will be 1, 2, 3, 4 and 5.
 Example: Create an array of size 5 and string type
and populate it with 5 names and display the
content of the array on a list box when a button is
clicked.
 The GUI of this application after running it should appear
the following figure:
5
string[] strFriends=new string[5];
//Populate the array
strFriends[0] = "Wendy“;
strFriends[1] = "Harriet“;
strFriends[2] = "Jay“;
strFriends[3] = "Michelle“;
strFriends[4] = "Richard“;
//Add the first array item to the list
lstFriends.Items.Add(strFriends[0]);
lstFriends.Items.Add(strFriends[1]);
lstFriends.Items.Add(strFriends[2]);
lstFriends.Items.Add(strFriends[3]);
lstFriends.Items.Add(strFriends[4]);

6
Using foreach . . . loop
• A foreach... is ideal for performing an operation on all ( or some )
elements of the array.
• A counter variable ( starting from the lower bound, stepping 1 and
ending at the upper bound ) can be used to dynamically and iteratively
express all indexes of all elements.
• E.g. 1
string[] strFriends = {“Elaine”, “Richard”, “Debra”, “Wendy”, “Harriet”};
//Add all array items to the list
foreach (string strName in strFriends)
lstFriends.Items.Add(strName);
Eg 2
• int[] nums={1,2,6,7};
• for (int num = 0; num <= nums.Length-1; num++)
• lstFriends.Items.Add(nums[num]);
7
Dynamic Array
• Being able to manipulate the size of an array from code,
and being able to store complex sets of data in an array is
important,
– but with .NET it’s far easier to achieve both of these
• Using Array.Resize();
• char[] array = new char[4];
• array[0] = 'p'; array[1] = 'e'; array[2] = 'r'; array[3]='b';
• // Resize the array from 4 to 2 element
• Array.Resize(ref array, 2);
• MessageBox.Show(array.Length.ToString());
– The code display 2

8
Multidimensional Arrays
• data_type var_Name[row, column ]=new data_type[r,c];
Example: Or
int[,] matrix = new int[2,4];
• int[,] matrix = matrix[0,0]=1;
matrix[0,1]=2;
• { {1, 2, 3, 4}, matrix[0,2]=3;
matrix[0,3]=4;
• {5, 6, 7, 8} }; matrix[1,0]=5;
matrix[1,1]=6;
matrix[1,2]=7;
matrix[1,3]=8;
• for (int row = 0; row < matrix.GetLength(0); row++)
• {
• for (int col = 0; col < matrix.GetLength(1); col++)
• { richTextBox1.Text+=Convert.ToString( (matrix[row, col]))+" "; }
• richTextBox1.Text += "\n";
• } 9
Jagged Arrays
• There are two types of multidimensional arrays—rectangular
and jagged.
• Rectangular arrays with two indices often represent tables of
values consisting of information arranged in rows and columns.
• Each row is the same size, and each column is the same size
(hence, the term “rectangular”).

10
Jagged Arrays…
• Jagged arrays are maintained as arrays of
arrays.
• Unlike rectangular arrays, rows in jagged
arrays can be of different lengths.
• In rectangular arrays, each row has the same
number of values. But this is not true for
jagged arrays.

11
Jagged Arrays, Example
int[][] jaggedArray = new int[3][];
• Before you can use jaggedArray, its elements must be
initialized. You can initialize the elements like this:
– jaggedArray[0] = new int[5];
– jaggedArray[1] = new int[4];
– jaggedArray[2] = new int[2];
• Each of the elements is a single-dimensional array of
integers. The first element is an array of 5 integers, the
second is an array of 4 integers, and the third is an array of
2 integers.
• It is also possible to use initializers to fill the array elements
with values, in which case you do not need the array size.
For example:
– jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
– jaggedArray[1] = new int[] { 0, 2, 4, 6 };
– jaggedArray[2] = new int[] { 11, 22 }; 12
Display the result
• for (int row = 0; row < jaggedArray.GetLength(0); row++)
• {
• for (int col = 0; col < jaggedArray[row].GetLength(0); col++)
• { richTextBox1.Text +=
Convert.ToString((jaggedArray[row] [col])) + " "; }
• richTextBox1.Text += "\n";
• }

13
Strings

• .NET Framework library provides classes to


work with strings and these classes are
common to all .NET language including C#
and VB.NET.
• The String Class represents character strings.
• The String data type comes from the
System.String class
• The String class is a sealed class , so you
cannot inherit another class from the String
class. 14
Strings…
• The String object is Immutable , it cannot be
modified once it created, that means every time you
use any operation in the String object , you create a
new String Object .
• So; if you are in a situation in continuous operation
with String Object, it is recommended to use
System.Text.StringBuilder .
• System.Text.StringBuilder class is used to modify a
string without creating a new object.
• Important methods of the class are described in
details in the following slides.
15
Exercise - Implement string functions
using the following interface

16
C# String Functions
Trim()
• The trim function has three variations Trim, TrimStart and TrimEnd. The first
example show how to use the Trim(). It strips all white spaces from both the
start and end of the string.
//STRIPS WHITE SPACES FROM BOTH START + FINSIHE
string Name = " String Manipulation " ;
string NewName = Name.Trim();
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");
TrimEnd()
• TrimEnd works in much the same way but you are stripping characters which
you specify from the end of the string, the below example first strips the
space then the n so the output is String Manipulatio.
• //STRIPS CHRS FROM THE END OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','n'};
string NewName = Name.TrimEnd(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");
17
TrimStart() : removes space at the beginning of a string.
Strings Functions
• IndexOf(string)
– Find String within string
• This code shows how to search within a string for a sub string and either
returns an index position of the start or -1 which indicates the string has not
been found. Or, 0 if the string searched is null.
• String str1 = "Lions, tigers and bears";
• string str2 = "tigers";
• int x = str1.IndexOf(str2);// …The value of x will be 7.
• MessageBox.Show(x.ToString());
• LastIndexOf(string)
– Finds the last position (or IndexOf) a character or string object in a string.
• string str1 = "No bananas, no bananas today.";
• string str2 = "bananas";
• int x = str1.LastIndexOf(str2);
• MessageBox.Show(x.ToString()); //x is 15
18
C# String Functions
• Contains (String)
– Tells you if a string Contains another string
– E.g.
• string str1 = "The student";
• string str2 = "student";
• bool bs;
• bs = str1.Contains(str2); //bs is true
• MessageBox.Show(bs.ToString());
• Concat (String1, String2)
• string str1 = "The student";
• string str2 = "is clever";
• string newStr = String.Concat(str1, str2);
• MessageBox.Show(newStr); 19
C# String Functions
• Insert (start index, String value)
– Inserts a string within another string at a specified starting point.
– E.g.
– string str1 = "Lions tigers and bears";
– string str2 = "and ";
– string NewString = String.Empty;
– NewString = str1.Insert(6, str2); //NewString will contain
"Lions and tigers and bears"
– MessageBox.Show(NewString);
• Replace (oldValue, newValue)
– Replace a set of characters or a string, from another string. E.g.
– string str1 = "Today is Wednesday";
– string oldValue = "Wednesday";
– string newValue = "Thursday";
– string NewString = str1.Replace(oldValue, newValue);//The
value is "Today is Thursday".
20
C# String Functions
• Join (separator, stringArray)
– Creates a single string from a string array.
– Join also sends a string containing the Separator value for the new
string.
– Join can also specify a starting index in the array and a count of
elements to extract. E.g:
• string[] arr = { "one", "two", "three" };
• string joinedStr=String.Join(",", arr);
• MessageBox.Show(joinedStr); //”one,two,three”
• Split (Separator)
– Takes a string and breaks it into a string array. Syntax:
ArrayName =str.Split(Delimiter[, Length Limit[, Compare Mode]]), where:
– Delimiter is an optional parameter that indicates what type of string
separates the elements in the input string. By default it is set to " ".
– Length Limit is the maximum size your output array can be.
– Compare mode: effects how the Delimiter parses Input String. By
default, compares character by ASCII values. 21
C# String Functions
E.g: string[] strCDRack;
• string cdList ="Nevermind, OK Computer, I Care
Because You Do";
• strCDRack = cdList.Split(',');
• foreach (string str in strCDRack)
– listBox1.Items.Add(str);
 Substring (start, length)
 Extract characters from the starting position for the
specified length. E.g.
• string str1 = "Today is Wednesday";
• string newstr = str1.Substring(0, 5);//return the string
Today.
• MessageBox.Show(newstr);
22
C# String Functions
 StartsWith (String)
 Determine if a string Starts With a specified character or string.
E.g.
• string str1 = "<h1> Heading </h1>";
• bool markup;
• string value = "<";
• markup = str1.StartsWith(value); // returns true.
 EndsWith(String )
 check if the Parameter String EndsWith the Specified String
 E.g. : "This is a Test".EndsWith("Test");// returns true
• Remove(index, count)
– Deletes a specified number of characters from a specified
position in a string. E.g.
• string s = "123abc000";
• MessageBox.Show(s.Remove(3, 3));// output is "123000" 23
C# String Functions
• Copy (String)
– The Copy method copies contents of a string to another. E.g.
• string str1="";
• string strRes = string.Copy(str1); //both are the same
• CopyTo(sourceIndex, Char Array, destIndex, Count)
– The CopyTo method copies a specified number of characters from a
specified position in this instance to a specified position in an array of
characters. E.g.
• string str1 = "ab";
• char[] chrs=new char[2];
• str1.CopyTo(0, chrs, 0, 2);
• foreach (char c in chrs)
• listBox1.Items.Add(c);
• ToUpper() and ToLower() E.g.:
• string aStr = "adgas";
• string strRes = aStr.ToUpper(); 24
C# String Functions
• Compare (String1, String2)
– The Compare method compares two strings and returns an integer
value.
• Less than zero When first string is less than second.
• Zero When both strings are equal.
• Greater than zero When first string is greater than the second.
E.g.
– string str1 = "ppp";
– string str2 = "ccc";
– int res = String.Compare(str1, str2);//…1 is returned
– MessageBox.Show(res.ToString());
• Equals (String str1, String str2) -returns Boolean value E.g.
– string Str1 = "Equals()";
– string Str2 = "Equals()";
– String.Equals(Str1,Str2); //returns true 25
C# String Functions
• Format (String, Object)
– You can use the Format method to create formatted strings
and concatenate multiple strings representing multiple
objects.
– The Format method automatically converts any passed
object into a string.
– E.g.
• Currency - MessageBox.Show(String.Format("{0:c}",
10));// will return $10.00
• Date - MessageBox.Show( String.Format("Today's date is
{0:D}", DateTime.Now));
– will return Today's date is like : 01 January 2005
• Time - MessageBox.Show(String.Format("The current
time is {0:T}", DateTime.Now));
– will return Current Time is Like : 10:10:12 26
C# String Functions
• PadLeft (width [, Character])
– PadLeft right-aligns the characters in a string and pads the
leftside to the specified length.
– If the default padding character is not specified, the padding
will be blanks. E.g.
• string str1 = "Chapter 1";
• string NewString=str1.PadLeft (15, '.');
• MessageBox.Show(NewString); //The Newstring is
"......Chapter.1"
• 15 is the total number of characters and remaining
characters
• PadRight (width [, Character])
– PadRight left-aligns the characters in a string and pads the
rightside to the specific length.
27
Other C# String Members
• Empty-variable
• string Emptystr = String.Empty;//Emptystr is now "".
• MessageBox.Show(Emptystr);
• Length-property
– Find the number of characters in a string.
– E.g.
• string str1 = "Today is Wednesday";
• int x = str1.Length; // …The value of x will be 18.
• MessageBox.Show(x.ToString());
• Reading:
– Other string Functions and Properties
– How to use System.Text.StringBuilder
– What is Regex and in what namespace it is found?
28

You might also like