Upcoming SlideShare
×

# Strings Arrays

1,937 views

Published on

4 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total views
1,937
On SlideShare
0
From Embeds
0
Number of Embeds
250
Actions
Shares
0
99
0
Likes
4
Embeds 0
No embeds

No notes for slide

### Strings Arrays

1. 1. Array String String Builder
2. 2. Arrays <ul><li>Arrays are collections of several elements of the same type </li></ul><ul><ul><li>E.g. 100 integers, 20 strings, 125 students, 12 dates, etc. </li></ul></ul><ul><ul><li>Single name is given to the entire array </li></ul></ul><ul><ul><li>But each element is accessed separately </li></ul></ul><ul><ul><li>Any element of a n array can be accessed just as quickly as any other element </li></ul></ul><ul><li>Arrays are homogeneous </li></ul><ul><ul><li>each item (sometimes called element ) has the same type </li></ul></ul><ul><ul><li>that type must be specified at declaration </li></ul></ul><ul><li>Items in an array are numbered (e.g. 1 st , 3 rd , or 105 th ) </li></ul><ul><ul><li>those are called index or subscript </li></ul></ul><ul><ul><li>numbering starts with 0 </li></ul></ul><ul><ul><li>we have to use the index value to refer an element in an array </li></ul></ul>
3. 3. Arrays <ul><li>Arrays are fixed-length entities. </li></ul><ul><ul><li>Length property gives the length of the array. </li></ul></ul><ul><ul><li>static Array.Resize resizes an array. It takes two arguments—the array to be resized and the new length. </li></ul></ul><ul><li>Arrays are reference types —what we typically think of as an array is actually a reference to an array object. </li></ul><ul><li>The elements of an array can be either value types or reference types. </li></ul><ul><ul><li>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. </li></ul></ul><ul><li>We access an array element specifying array’s name and element’s index (position in the array). </li></ul><ul><ul><li>Index starts at 0 (zero) . </li></ul></ul><ul><ul><li>CLR performs bounds checking for you and throws IndexOutOfRangeException . </li></ul></ul>
4. 4. Examples <ul><li>See Array.cs </li></ul><ul><li>int[] counter = new int[9]; </li></ul><ul><ul><li>char[] letters = new char[12]; </li></ul></ul><ul><li>string[] strArray = new string[5]; </li></ul><ul><li>Dice[] diceArray = new Dice[4]; </li></ul><ul><li>int[] c; c = new int[12]; </li></ul>0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 null null null null null null null null null 0 1 2 3 4 5 6 7 8 counter 0 1 2 3 4 5 6 7 8 9 10 11 letters 0 1 2 3 4 strArray 0 1 2 3 diceArray
5. 5. How to reach a single array element <ul><li>specify the index value within square brackets after the vector/array name </li></ul><ul><ul><li>var_name [ index_expr ] </li></ul></ul><ul><ul><li>the value of index expression must be between 0 and (array size – 1) </li></ul></ul><ul><ul><li>.NET performs bounds checking for you and throws IndexOutOfRangeException . </li></ul></ul><ul><li>Examples </li></ul><ul><ul><li>int[] nums = new int(9); </li></ul></ul><ul><ul><li>nums[5] = 102; </li></ul></ul><ul><ul><li>nums[0] = nums[5]*2-1; </li></ul></ul><ul><ul><li>nums[nums[5]/20-3] = 55; </li></ul></ul><ul><ul><li>nums[10] = 5; </li></ul></ul><ul><ul><li>// exception </li></ul></ul>nums 102 203 55 0 1 2 3 4 5 6 7 8
6. 6. Array Element Access <ul><li>for (int i = 0; i < counter.Length; i++) </li></ul><ul><ul><ul><li>Console.WriteLine(&quot;{0} {1}&quot;, i, counter[i]); </li></ul></ul></ul><ul><li>int[] array = new int[10]; </li></ul><ul><li>for (int i = 0; i < array.Length; i++) </li></ul><ul><li>array[i] = 2 + 2 * i; </li></ul><ul><li>Dice[] diceArray = new Dice[4]; </li></ul><ul><li>for (int i = 0; i < diceArray.Length; i++) </li></ul><ul><li>{ </li></ul><ul><li>diceArray[i] = new Dice(6); </li></ul><ul><li>diceArray[i].Roll(); </li></ul><ul><li> } </li></ul>
7. 7. Array Initializers <ul><li>int[] array = {32, 27, 64, 18, 95, 14, 90, 70, 60}; </li></ul>32 27 64 18 95 14 90 70 60 0 1 2 3 4 5 6 7 8 array
8. 8. Passing Arrays and Array Elements to Methods as Parameters <ul><li>To pass an array argument to a method, specify the name of the array without any brackets. For a method to receive an array reference through a method call, the method’s parameter list must specify an array parameter. </li></ul><ul><li>When an argument to a method is an entire array or an individual array element of a reference type, the called method receives a copy of the reference. </li></ul><ul><li>When an argument to a method is an individual array element of a value type, the called method receives a copy of the element’s value. </li></ul><ul><li>To pass an individual array element to a method, use the indexed name of the array as an argument in the method call. </li></ul><ul><li>Example: ArrayParameter.cs </li></ul>
9. 9. foreach <ul><li>The foreach statement iterates through the elements of an entire array or collection. </li></ul><ul><ul><li>foreach ( type identifier in arrayName ) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li><s tatement1> ; </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>< statementN> ; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>type and identifier are the type and name (e.g. int number ) of the iteration variable . </li></ul></ul><ul><li>The type of the iteration variable must match the type of the elements in the array. </li></ul><ul><li>The iteration variable represents successive values in the array on successive iterations of the foreach statement. </li></ul>
10. 10. Example: foreach.cs <ul><li>int[] array = {87, 68, 94, 100, 83, 78, 85, 91, 76}; </li></ul><ul><li>int total = 0; </li></ul><ul><li>// add each element's value to total </li></ul><ul><li>foreach ( int number in array ) </li></ul><ul><li>total += number; </li></ul>
11. 11. Implicitly Typed Variables <ul><li>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. </li></ul><ul><li>To distinguish such an initialization from a simple assignment statement, the var keyword is used in place of the variable’s type. </li></ul><ul><li>You can use local type inference with control variables in the header of a for or foreach statement. </li></ul><ul><li>if myArray is an array of ints, the following foreach statement headers are equivalent: </li></ul><ul><ul><li>foreach ( int number in myArray) </li></ul></ul><ul><ul><li>foreach ( var number in myArray) </li></ul></ul>
12. 12. System.String <ul><li>string is the alias for System.String </li></ul><ul><li>A string is an object of class string in the System namespace representing a series of characters. </li></ul><ul><li>These characters can be uppercase letters, lowercase letters, digits and various special characters . </li></ul><ul><li>Character constants are established according to the Unicode character set . </li></ul><ul><li>String is a reference type. </li></ul><ul><li>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. </li></ul>
13. 13. StringConstructor.cs <ul><li>Class string provides 8 constructors. Below is the use of 3 constructors: </li></ul>Assign a string literal to string reference originalString. The string constructor can take a char array and two int arguments for starting position and length. Copy a reference to another string literal. The string constructor can take a character array as an argument. The string constructor can take as arguments a character and an int specifying the number of times to repeat that character in the string .
14. 14. String Properties <ul><li>Property Length allows you to determine the number of characters in a string. </li></ul><ul><li>The string indexer treats a string as an array of chars and returns each character at a specific position in the string. </li></ul><ul><li>As with arrays, the first element of a string is considered to be at position 0. </li></ul><ul><ul><li>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 . </li></ul></ul><ul><li>The string method CopyTo copies a specified number of characters from a string into a char array. </li></ul><ul><li>StringMethods.cs </li></ul>
15. 15. Comparing Strings <ul><li>Method Equals tests any two objects for equality (i.e., checks whether the objects contain identical contents). </li></ul><ul><li>The string class’s Equals method uses a lexicographical comparison —comparing the integer Unicode values of character in each string. </li></ul><ul><li>The overloaded string equality operator == also uses a lexicographical comparison to compare two strings. </li></ul><ul><li>String comparisons are case-sensitive. </li></ul><ul><li>Method CompareTo returns: </li></ul><ul><ul><li>0 if the strings are equal </li></ul></ul><ul><ul><li>A negative value if the calling string is less than the argument string </li></ul></ul><ul><ul><li>A positive value if the calling string is greater than the argument. </li></ul></ul><ul><li>Example: StringCompare.cs </li></ul>
16. 16. Searching Strings <ul><li>StartWith and EndWith </li></ul><ul><ul><li>string s = “started”; </li></ul></ul><ul><ul><li>if ( s.StartsWith(“st”) ) </li></ul></ul><ul><ul><li>… </li></ul></ul><ul><ul><li>if ( s.EndsWith(“ed”) ) </li></ul></ul><ul><ul><li>… </li></ul></ul><ul><li>IndexOf </li></ul><ul><ul><li>locates the first occurrence of a character or substring in a string and returns its index, or -1 if it is not found. </li></ul></ul><ul><li>LastIndexOf </li></ul><ul><ul><li>like IndexOf , but searches from the end of the string. </li></ul></ul><ul><li>IndexOfAny and LastIndexOfAny </li></ul><ul><ul><li>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. </li></ul></ul>
17. 17. Substring and Concat <ul><li>Substring methods which create a new string by copying part of an existing string. </li></ul><ul><ul><li>s.Substr(20); </li></ul></ul><ul><ul><li>s.Substr(0, 6); </li></ul></ul><ul><li>Like the + operator , the static method Concat of class string concatenates two strings and returns a new string. </li></ul><ul><ul><li>string strNew = String.Concat(str1, str2); </li></ul></ul><ul><ul><li>String strNew = str1 + str2; </li></ul></ul><ul><li>String[] words = sentence. Split (' '); </li></ul><ul><li>string2 = string1. Replace (‘e’, ‘E’); </li></ul><ul><li>string2 = string1. ToUpper () and </li></ul><ul><ul><li>string2 = string1. ToLower () </li></ul></ul><ul><li>string2 = string1. Trim (); </li></ul><ul><li>Examples: StringMethods2.cs </li></ul>
18. 18. StringBuilder <ul><li>Objects of class string are immutable. </li></ul><ul><li>Class StringBuilder is used to create and manipulate dynamic string information—i.e., mutable strings. </li></ul><ul><li>StringBuilder is much more efficient for working with large numbers of strings than creating individual immutable strings . </li></ul>
19. 19. StringBuilder constructors <ul><li>The no-parameter StringBuilder constructor creates an empty StringBuilder with a default capacity of 16 characters. </li></ul><ul><li>Given a single int argument, the StringBuilder constructor creates an empty StringBuilder that has the initial capacity specified in the int argument. </li></ul><ul><li>Given a single string argument, the StringBuilder constructor creates a StringBuilder containing the characters of the string argument. </li></ul><ul><ul><li>Its initial capacity is the smallest power of two greater than or equal to the number of characters in the argument string, with a minimum of 16. </li></ul></ul>
20. 20. StringBuilder features <ul><li>Class StringBuilder provides the Length and Capacity properties. </li></ul><ul><li>Method EnsureCapacity doubles the StringBuilder instance’s current capacity. </li></ul><ul><ul><li>If this doubled value is greater than the value that the programmer wishes to ensure, that value becomes the new capacity. </li></ul></ul><ul><ul><li>Otherwise, EnsureCapacity alters the capacity to make it equal to the requested number. </li></ul></ul><ul><li>When a StringBuilder exceeds its capacity, it grows in the same manner as if method EnsureCapacity had been called. </li></ul><ul><li>If Length is set to a value less than the number of characters in the StringBuilder , the contents of the StringBuilder are truncated. </li></ul>
21. 21. Append and AppendFormat <ul><li>Class StringBuilder provides 19 overloaded Append methods that allow various types of values to be added to the end of a StringBuilder. </li></ul><ul><ul><li>The Framework Class Library provides versions for each of the simple types and for character arrays, strings and objects. </li></ul></ul><ul><li>Examples: StringBuilderAppend.cs </li></ul><ul><li>AppendFormat converts a string to a specified format, then appends it to the StringBuilder. </li></ul><ul><li>Examples: StringBuilderAppendFormat.cs </li></ul>
22. 22. Append and AppendFormat <ul><li>Formats have the form {X[,Y][:FormatString]}. </li></ul><ul><ul><li>X is the number of the argument to be formatted, counting from zero. </li></ul></ul><ul><ul><li>Y is an optional argument, which can be positive or negative, indicating how many characters should be in the result. </li></ul></ul><ul><ul><li>A positive integer aligns the string to the right; a negative integer aligns it to the left. </li></ul></ul><ul><ul><li>The optional FormatString applies a particular format to the argument—currency, decimal or scientific, among others. </li></ul></ul><ul><li>One version of AppendFormat takes a string specifying the format and an array of objects to serve as the arguments to the format string. </li></ul>
23. 23. Other Methods of StringBuilder <ul><li>Insert </li></ul><ul><ul><li>inserts its second argument into the StringBuilder in front of the character in the position specified by the first argument. </li></ul></ul><ul><li>Remove </li></ul><ul><ul><li>takes two arguments—the index at which to begin deletion and the number of characters to delete. </li></ul></ul><ul><li>Replace </li></ul><ul><ul><li>searches for a specified string or character and substitutes another string or character in its place. </li></ul></ul>
24. 24. char Methods <ul><li>char is an alias for the struct Char . </li></ul><ul><li>Char method IsDigit determines whether a character is defined as a digit. </li></ul><ul><li>IsLetter determines whether a character is a letter. </li></ul><ul><li>IsLetterOrDigit determines whether a character is a letter or a digit. </li></ul><ul><li>IsLower determines whether a character is a lowercase letter. </li></ul><ul><li>IsUpper determines whether a character is an uppercase letter. </li></ul><ul><li>ToUpper returns a character’s uppercase equivalent, or the original argument if there is no uppercase equivalent. </li></ul>
25. 25. char Methods <ul><li>ToLower returns a character lowercase equivalent, or the original argument if there is no lowercase equivalent. </li></ul><ul><li>IsPunctuation determines whether a character is a punctuation mark, such as &quot;!&quot;, &quot;:&quot; or &quot;)&quot;. </li></ul><ul><li>IsSymbol determines whether a character is a symbol, such as &quot;+&quot;, &quot;=&quot; or &quot;^&quot;. </li></ul><ul><li>Static method IsWhiteSpace . </li></ul><ul><li>Public instance methods: ToString , Equals , and CompareTo . </li></ul>
26. 26. Multidimensional Arrays <ul><li>2-dimensional rectangular array: </li></ul><ul><li>An array with m rows and n columns is called an m-by-n array . </li></ul><ul><li>Every element in array a is identified by an array-access expression of the form a[  row,   column  ]; </li></ul><ul><li>A two-by-two rectangular array b can be declared and initialized as follows: </li></ul><ul><li>int[ , ] b = { { 1, 2 } , { 3, 4 } }; </li></ul><ul><ul><li>The initializer values are grouped by row in braces. </li></ul></ul>
27. 27. Jagged Arrays <ul><li>A jagged array is a one-dimensional array whose elements are one-dimensional arrays. </li></ul><ul><li>The lengths of the rows in the array need not be the same. </li></ul><ul><li>A jagged array with three rows of different lengths could be declared and initialized as follows: </li></ul><ul><ul><li>int[][] jagged = { new int[] { 1, 2 }, new int[] { 3 }, new int[] { 4, 5, 6 } }; </li></ul></ul>
28. 28. Multidimensional Arrays <ul><li>A rectangular array can be created with an array-creation expression: </li></ul><ul><ul><li>int [ , ] b; </li></ul></ul><ul><ul><li>b = new int [ 3 , 4 ]; </li></ul></ul><ul><li>A jagged array cannot be completely created with a single array-creation expression. Each one-dimensional array must be initialized separately. </li></ul><ul><li>A jagged array can be created as follows: </li></ul><ul><ul><li>int [][] c; </li></ul></ul><ul><ul><li>c = new int [ 2 ][ ]; // create 2 rows </li></ul></ul><ul><ul><li>c[ 0 ] = new int [ 5 ]; // create 5 columns for row 0 </li></ul></ul><ul><ul><li>c[ 1 ] = new int [ 3 ]; // create 3 columns for row 1 </li></ul></ul>
29. 29. Searching an array <ul><li>We can search for one occurrence, return true/false or the index of occurrence </li></ul><ul><ul><li>Search the array starting from the beginning </li></ul></ul><ul><ul><li>S top searching when match is found </li></ul></ul><ul><li>We can search and count the number of occurrences and return count </li></ul><ul><ul><li>Search entire array </li></ul></ul><ul><ul><li>Similar to one occurrence search, but do not stop after first occurrence </li></ul></ul><ul><li>We can search for many occurrences, but return occurrences in another array rather than count </li></ul><ul><li>In all these cases, we search the array sequentially starting from the beginning </li></ul><ul><ul><li>This type of search is called “sequential search” </li></ul></ul>
30. 30. Counting search <ul><li>static int CountMatches(string[] a, string s) </li></ul><ul><li>{ </li></ul><ul><li> int count = 0; </li></ul><ul><li>for (int k = 0; k < a.Length; k++) </li></ul><ul><li>{ </li></ul><ul><li>if (a[k] == s) </li></ul><ul><li>{ </li></ul><ul><li>count++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>return count; </li></ul><ul><li>} </li></ul><ul><li>How can we change this code to return the index of the first occurrence? </li></ul><ul><ul><li>see next slide </li></ul></ul>
31. 31. One occurrence search <ul><li>static int FirstMatch(string[] a, string s) </li></ul><ul><li>{ </li></ul><ul><li>for (int k = 0; k < a.Length; k++) </li></ul><ul><li>{ </li></ul><ul><li>if (a[k] == s) </li></ul><ul><li>{ </li></ul><ul><li>return k; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>return -1; </li></ul><ul><li>} </li></ul><ul><li>Does not search the entire array if one match is found </li></ul><ul><ul><li>good for efficiency purposes </li></ul></ul><ul><li>How could you modify this to return true/false? </li></ul>
32. 32. Collecting search <ul><li>Collect the occurrences of a string in another vector and return it </li></ul><ul><li>static string[] Collect(string[] inVector, string find) </li></ul>
33. 33. Binary search <ul><li>Alternative to sequential search for sorted vectors </li></ul><ul><li>If a vector is sorted we can use the sorted property to eliminate half of the vector elements with one comparison </li></ul><ul><ul><li>What number (between 1 and 100) do we guess first in number guessing game ? </li></ul></ul><ul><li>Idea of creating program to do binary search </li></ul><ul><ul><li>Check the middle element </li></ul></ul><ul><ul><ul><li>If it has the searched value, then you’re done! </li></ul></ul></ul><ul><ul><ul><li>If not, eliminate half of the elements of the vector </li></ul></ul></ul><ul><ul><li>search the rest using the same idea </li></ul></ul><ul><ul><li>continue until match is found or there is no match </li></ul></ul><ul><ul><ul><li>how could you understand that there is no match? </li></ul></ul></ul><ul><ul><li>let’s develop the algorithm on an example </li></ul></ul><ul><ul><ul><li>we need two index values, low and high, for the search space </li></ul></ul></ul><ul><li>Array.BinarySearch </li></ul>
34. 34. Sorting an Array <ul><li>One of the fundamental operations in Computer Science </li></ul><ul><li>Given a randomly ordered array, sort it </li></ul><ul><ul><li>ascending </li></ul></ul><ul><ul><li>descending </li></ul></ul><ul><ul><li>Array.Sort </li></ul></ul>
35. 35. Array Exercise <ul><li>Consider the following example: </li></ul><ul><ul><li>generate a random number [1..6] and count the number of occurrences of all outcomes (1, 2, 3, 4, 5, 6) </li></ul></ul><ul><ul><li>Repeat this 6000 times and display statistics </li></ul></ul>
36. 36. Variable-length argument lists <ul><li>Variable-length argument lists allow you to create methods that receive an arbitrary number of arguments. </li></ul><ul><li>The necessary params modifier can occur only in the last entry of the parameter list. </li></ul><ul><li>Example: ParamArrayTest.cs </li></ul>
37. 37. Command-line Arguments <ul><li>You can pass command-line arguments to an application by including a parameter of type string[] in the parameter list of Main . </li></ul><ul><li>By convention, this parameter is named args . </li></ul><ul><li>The execution environment passes the command-line argu­ments as an array to the application’s Main method. </li></ul><ul><li>The number of arguments passed from the command line is obtained by accessing the array’s Length property. </li></ul><ul><li>Command-line arguments are separated by white space, not commas. </li></ul><ul><li>Example: VarargsTest.cs </li></ul>
38. 38. enum <ul><li>An enumerated type is a value type that defines a set of symbolic name and value pairs. </li></ul><ul><li>For example: enum type identifying a single color: </li></ul><ul><ul><li>public enum Color </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>White, // Assigned a value of 0 </li></ul></ul><ul><ul><li>Red, // Assigned a value of 1 </li></ul></ul><ul><ul><li>Green, // Assigned a value of 2 </li></ul></ul><ul><ul><li>Blue, // Assigned a value of 3 </li></ul></ul><ul><ul><li>Orange, // Assigned a value of 4 </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>Other examples: days/months, cards types, states in a game, etc. etc. </li></ul><ul><li>Let’s see example code: enum.cs </li></ul>
39. 39. System.Enum methods <ul><li>public static bool IsDefined(Type enumType, object value); </li></ul><ul><li>public static object Parse(Type enumType, string value); </li></ul><ul><li>public static object Parse(Type enumType, string value, </li></ul><ul><li>bool ignoreCase); </li></ul><ul><li>public static string GetName(Type enumType, object value); </li></ul><ul><li>public static string[] GetNames(Type enumType); </li></ul><ul><li>public static Array GetValues(Type enumType); </li></ul><ul><li>public int CompareTo(object target); </li></ul><ul><li>public static string Format(Type enumType, object value, </li></ul><ul><li> string format); </li></ul><ul><li>public override string ToString(); </li></ul><ul><li>public static object ToObject(Type enumType, int value); </li></ul><ul><li>// many overloads </li></ul>