Array String Builder Arrays are collections of several
Array String Builder
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
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 Index. Out. Of. Range. Exception.
Examples See Array. cs counter int[] counter = new int[9]; 0 0 1 2 0 3 0 0 0 4 5 6 7 8 0 0 7 8 9 10 11 letters char[] letters = new char[12]; 0 0 0 0 1 2 3 4 5 string[] str. Array = new string[5]; null 1 2 Dice[] dice. Array = new Dice[4]; null 3 dice. Array null int[] c; c = new int[12]; 6 str. Array 0 0 0 null 1 2 3 4 0
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 Index. Out. Of. Range. Exception. Examples int[] nums = new int(9); nums[5] = 102; nums[0] = nums[5]*2 -1; nums[5]/20 -3] = 55; nums[10] = 5; // exception 203 0 55 1 2 102 3 4 5 6 7 8
Array Element Access for (int i = 0; i < counter. Length; i++) Console. Write. Line("{0} {1}", i, counter[i]); int[] array = new int[10]; for (int i = 0; i < array. Length; i++) array[i] = 2 + 2 * i; Dice[] dice. Array = new Dice[4]; for (int i = 0; i < dice. Array. Length; i++) { dice. Array[i] = new Dice(6); dice. Array[i]. Roll(); }
Array Initializers int[] array = {32, 27, 64, 18, 95, 14, 90, 70, 60}; array 32 27 64 18 95 14 90 70 60 0 6 1 2 3 4 5 7 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: Array. Parameter. cs
foreach The foreach statement iterates through the elements of an entire array or collection. foreach (type identifier in array. Name ) { <statement 1>; . . . <statement. N>; } 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. 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;
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 my. Array is an array of ints, the following foreach statement headers are equivalent: foreach (int number in my. Array) foreach (var number in my. Array)
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.
String. Constructor. cs • Class string provides 8 constructors. Below is the use of 3 constructors: Assign a string literal to string reference original. String. 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 Index. Out. Of. Range. Exception. • The string method Copy. To copies a specified number of characters from a string into a char array. • String. Methods. 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 Compare. To 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: String. Compare. cs
Searching Strings Start. With and End. With string s = “started”; if ( s. Starts. With(“st”) ) … if ( s. Ends. With(“ed”) ) … Index. Of locates the first occurrence of a character or substring in a string and returns its index, or 1 if it is not found. Last. Index. Of like Index. Of, but searches from the end of the string. Index. Of. Any and Last. Index. Of. Any 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 str. New = String. Concat(str 1, str 2); String str. New = str 1 + str 2; String[] words = sentence. Split(' '); string 2 = string 1. Replace(‘e’, ‘E’); string 2 = string 1. To. Upper() and string 2 = string 1. To. Lower() string 2 = string 1. Trim(); Examples: String. Methods 2. cs
String. Builder Objects of class string are immutable. Class String. Builder is used to create and manipulate dynamic string information—i. e. , mutable strings. String. Builder is much more efficient for working with large numbers of strings than creating individual immutable strings.
String. Builder constructors • The no parameter String. Builder constructor creates an empty String. Builder with a default capacity of 16 characters. • Given a single int argument, the String. Builder constructor creates an empty String. Builder that has the initial capacity specified in the int argument. • Given a single string argument, the String. Builder constructor creates a String. Builder 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.
String. Builder features Class String. Builder provides the Length and Capacity properties. Method Ensure. Capacity doubles the String. Builder 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, Ensure. Capacity alters the capacity to make it equal to the requested number. When a String. Builder exceeds its capacity, it grows in the same manner as if method Ensure. Capacity had been called. If Length is set to a value less than the number of characters in the String. Builder , the contents of the String. Builder are truncated.
Append and Append. Format Class String. Builder provides 19 overloaded Append methods that allow various types of values to be added to the end of a String. Builder. The Framework Class Library provides versions for each of the simple types and for character arrays, strings and objects. Examples: String. Builder. Append. cs Append. Format converts a string to a specified format, then appends it to the String. Builder. Examples: String. Builder. Append. Format. cs
Append and Append. Formats have the form {X[, Y][: Format. String]}. 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 Format. String applies a particular format to the argument—currency, decimal or scientific, among others. One version of Append. Format takes a string specifying the format and an array of objects to serve as the arguments to the format string.
Other Methods of String. Builder Insert inserts its second argument into the String. Builder 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.
char Methods char is an alias for the struct Char method Is. Digit determines whether a character is defined as a digit. Is. Letter determines whether a character is a letter. Is. Letter. Or. Digit determines whether a character is a letter or a digit. Is. Lower determines whether a character is a lowercase letter. Is. Upper determines whether a character is an uppercase letter. To. Upper returns a character’s uppercase equivalent, or the original argument if there is no uppercase equivalent.
char Methods To. Lower returns a character lowercase equivalent, or the original argument if there is no lowercase equivalent. Is. Punctuation determines whether a character is a punctuation mark, such as "!", ": " or ")". Is. Symbol determines whether a character is a symbol, such as "+", "=" or "^". Static method Is. White. Space. Public instance methods: To. String, Equals, and Compare. To.
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.
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 } };
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
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”
Counting search static int Count. Matches(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
One occurrence search static int First. Match(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?
Collecting search Collect the occurrences of a string in another vector and return it static string[] Collect(string[] in. Vector, string find)
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. Binary. Search
Sorting an Array One of the fundamental operations in Computer Science Given a randomly ordered array, sort it ascending descending Array. Sort
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
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: Param. Array. Test. cs
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: Varargs. Test. cs
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 Red, // Assigned a value of Green, // Assigned a value of Blue, // Assigned a value of Orange, // Assigned a value of } 0 1 2 3 4 Other examples: days/months, cards types, states in a game, etc. Let’s see example code: enum. cs
System. Enum methods public static bool Is. Defined(Type enum. Type, object value); public static object Parse(Type enum. Type, string value, bool ignore. Case); public static string Get. Name(Type enum. Type, object value); public static string[] Get. Names(Type enum. Type); public static Array Get. Values(Type enum. Type); public int Compare. To(object target); public static string Format(Type enum. Type, object value, string format); public override string To. String(); public static object To. Object(Type enum. Type, int value); // many overloads
- Slides: 39