Presentation is loading. Please wait.

Presentation is loading. Please wait.

Array String String Builder. Arrays Arrays are collections of several elements of the same type E.g. 100 integers, 20 strings, 125 students, 12 dates,

Similar presentations


Presentation on theme: "Array String String Builder. Arrays Arrays are collections of several elements of the same type E.g. 100 integers, 20 strings, 125 students, 12 dates,"— Presentation transcript:

1 Array String String Builder

2 Arrays Arrays are collections of several elements of the same type E.g. 100 integers, 20 strings, 125 students, 12 dates, etc. Single name is given to the entire array But each element is accessed separately Any element of an array can be accessed just as quickly as any other element Arrays are homogeneous each item (sometimes called element) has the same type that type must be specified at declaration Items in an array are numbered (e.g. 1 st, 3 rd, or 105 th ) those are called index or subscript numbering starts with 0 we have to use the index value to refer an element in an array

3 Arrays Arrays are fixed-length entities. 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. 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.

4 Examples See Array.cs int[] counter = new int[9]; char[] letters = new char[12]; string[] strArray = new string[5]; Dice[] diceArray = new Dice[4]; int[] c; c = new int[12]; 0 1 2 3 4 5 6 7 8 counter 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 letters 0 0 0 0 0 0 0 1 2 3 4 strArray null null null null null 0 1 2 3 diceArray null null

5 How to reach a single array element specify the index value within square brackets after the vector/array name var_name [index_expr] the value of index expression must be between 0 and (array size – 1).NET performs bounds checking for you and throws IndexOutOfRangeException. Examples int[] nums = new int(9); nums[5] = 102; nums[0] = nums[5]*2-1; nums[nums[5]/20-3] = 55; nums[10] = 5; // exception 0 1 2 3 4 5 6 7 8 nums 102 203 55

6 Array Element Access for (int i = 0; i < counter.Length; i++) Console.WriteLine("{0} {1}", i, counter[i]); int[] array = new int[10]; for (int i = 0; i < array.Length; i++) array[i] = 2 + 2 * i; Dice[] diceArray = new Dice[4]; for (int i = 0; i < diceArray.Length; i++) { diceArray[i] = new Dice(6); diceArray[i].Roll(); }

7 Array Initializers int[] array = {32, 27, 64, 18, 95, 14, 90, 70, 60}; 0 1 2 3 4 5 6 7 8 array 32 27 64 18 95 14 90 70 60

8 Passing Arrays and Array Elements to Methods as Parameters 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. 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. 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. To pass an individual array element to a method, use the indexed name of the array as an argument in the method call. Example: ArrayParameter.cs

9 foreach The foreach statement iterates through the elements of an entire array or collection. foreach (type identifier in arrayName ) { ;... ; } 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.

10 Example: foreach.cs 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;

11 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)

12 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.

13 StringConstructor.cs Class string provides 8 constructors. Below is the use of 3 constructors: 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 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

15 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

16 Searching Strings 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.

17 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; String[] words = sentence.Split(' '); string2 = string1.Replace(‘e’, ‘E’); string2 = string1.ToUpper() and string2 = string1.ToLower() string2 = string1.Trim(); Examples: StringMethods2.cs

18 StringBuilder Objects of class string are immutable. Class StringBuilder is used to create and manipulate dynamic string information—i.e., mutable strings. StringBuilder is much more efficient for working with large numbers of strings than creating individual immutable strings.

19 StringBuilder constructors The no-parameter StringBuilder constructor creates an empty StringBuilder with a default capacity of 16 characters. Given a single int argument, the StringBuilder constructor creates an empty StringBuilder that has the initial capacity specified in the int argument. Given a single string argument, the StringBuilder constructor creates a StringBuilder containing the characters of the string argument. 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.

20 StringBuilder features Class StringBuilder provides the Length and Capacity properties. Method EnsureCapacity doubles the StringBuilder instance’s current capacity. If this doubled value is greater than the value that the programmer wishes to ensure, that value becomes the new capacity. Otherwise, EnsureCapacity alters the capacity to make it equal to the requested number. When a StringBuilder exceeds its capacity, it grows in the same manner as if method EnsureCapacity had been called. If Length is set to a value less than the number of characters in the StringBuilder, the contents of the StringBuilder are truncated.

21 Append and AppendFormat Class StringBuilder provides 19 overloaded Append methods that allow various types of values to be added to the end of a StringBuilder. The Framework Class Library provides versions for each of the simple types and for character arrays, strings and objects. Examples: StringBuilderAppend.cs AppendFormat converts a string to a specified format, then appends it to the StringBuilder. Examples: StringBuilderAppendFormat.cs

22 Append and AppendFormat Formats have the form {X[,Y][:FormatString]}. X is the number of the argument to be formatted, counting from zero. Y is an optional argument, which can be positive or negative, indicating how many characters should be in the result. A positive integer aligns the string to the right; a negative integer aligns it to the left. The optional FormatString applies a particular format to the argument—currency, decimal or scientific, among others. One version of AppendFormat takes a string specifying the format and an array of objects to serve as the arguments to the format string.

23 Other Methods of StringBuilder Insert inserts its second argument into the StringBuilder in front of the character in the position specified by the first argument. Remove takes two arguments—the index at which to begin deletion and the number of characters to delete. Replace searches for a specified string or character and substitutes another string or character in its place.

24 char Methods char is an alias for the struct Char. 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.

25 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.

26 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.

27 Jagged Arrays A jagged array is a one-dimensional array whose elements are one-dimensional arrays. The lengths of the rows in the array need not be the same. A jagged array with three rows of different lengths could be declared and initialized as follows: int[][] jagged = { new int[] { 1, 2 }, new int[] { 3 }, new int[] { 4, 5, 6 } };

28 Multidimensional Arrays A rectangular array can be created with an array-creation expression: int[, ] b; b = new int[ 3, 4 ]; A jagged array cannot be completely created with a single array- creation expression. Each one-dimensional array must be initialized separately. A jagged array can be created as follows: int[][] c; c = new int[ 2 ][ ]; // create 2 rows c[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 c[ 1 ] = new int[ 3 ]; // create 3 columns for row 1

29 Searching an array We can search for one occurrence, return true/false or the index of occurrence Search the array starting from the beginning Stop searching when match is found We can search and count the number of occurrences and return count Search entire array Similar to one occurrence search, but do not stop after first occurrence We can search for many occurrences, but return occurrences in another array rather than count In all these cases, we search the array sequentially starting from the beginning This type of search is called “sequential search”

30 Counting search static int CountMatches(string[] a, string s) { int count = 0; for (int k = 0; k < a.Length; k++) { if (a[k] == s) { count++; } return count; } How can we change this code to return the index of the first occurrence? see next slide

31 One occurrence search static int FirstMatch(string[] a, string s) { for (int k = 0; k < a.Length; k++) { if (a[k] == s) { return k; } return -1; } Does not search the entire array if one match is found good for efficiency purposes How could you modify this to return true/false?

32 Collecting search Collect the occurrences of a string in another vector and return it static string[] Collect(string[] inVector, string find)

33 Binary search Alternative to sequential search for sorted vectors If a vector is sorted we can use the sorted property to eliminate half of the vector elements with one comparison What number (between 1 and 100) do we guess first in number guessing game? Idea of creating program to do binary search Check the middle element If it has the searched value, then you’re done! If not, eliminate half of the elements of the vector search the rest using the same idea continue until match is found or there is no match how could you understand that there is no match? let’s develop the algorithm on an example we need two index values, low and high, for the search space Array.BinarySearch

34 Sorting an Array One of the fundamental operations in Computer Science Given a randomly ordered array, sort it ascending descending Array.Sort

35 Array Exercise Consider the following example: generate a random number [1..6] and count the number of occurrences of all outcomes (1, 2, 3, 4, 5, 6) Repeat this 6000 times and display statistics

36 Variable-length argument lists Variable-length argument lists allow you to create methods that receive an arbitrary number of arguments. The necessary params modifier can occur only in the last entry of the parameter list. Example: ParamArrayTest.cs

37 Command-line Arguments You can pass command-line arguments to an application by including a parameter of type string[] in the parameter list of Main. By convention, this parameter is named args. The execution environment passes the command-line argu­ments as an array to the application’s Main method. The number of arguments passed from the command line is obtained by accessing the array’s Length property. Command-line arguments are separated by white space, not commas. Example: VarargsTest.cs

38 enum An enumerated type is a value type that defines a set of symbolic name and value pairs. For example: enum type identifying a single color: public enum Color { White, // Assigned a value of 0 Red, // Assigned a value of 1 Green, // Assigned a value of 2 Blue, // Assigned a value of 3 Orange, // Assigned a value of 4 } Other examples: days/months, cards types, states in a game, etc. etc. Let’s see example code: enum.cs

39 System.Enum methods public static bool IsDefined(Type enumType, object value); public static object Parse(Type enumType, string value); public static object Parse(Type enumType, string value, bool ignoreCase); public static string GetName(Type enumType, object value); public static string[] GetNames(Type enumType); public static Array GetValues(Type enumType); public int CompareTo(object target); public static string Format(Type enumType, object value, string format); public override string ToString(); public static object ToObject(Type enumType, int value); // many overloads


Download ppt "Array String String Builder. Arrays Arrays are collections of several elements of the same type E.g. 100 integers, 20 strings, 125 students, 12 dates,"

Similar presentations


Ads by Google