0% found this document useful (0 votes)
61 views

Arrays

Magic of C# with .Net Framework

Uploaded by

Priti Dimri
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF or read online on Scribd
0% found this document useful (0 votes)
61 views

Arrays

Magic of C# with .Net Framework

Uploaded by

Priti Dimri
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF or read online on Scribd
You are on page 1/ 16
Arrays Inthe, weil tay te tres Araya Sings in¥Araysare ey ip tan and are very handy atthe ine of ramming Inf the aray manipulations le Aiferent from the tational ways. Therefore, we decided to devote half ofthis chapter What is an Array through sof the array A aray i a data structure that exntains a numberof variable which area ‘computed indies. The variables contained in an aray ls called the element areal ofthe same type, and thie types ale the element type ofthe array thas arank which determines the number of indices assciated with each array element. The rankofan arrays also refered to asthe dimension ofthe aay. An array witha rank afoneis called a single dimensinal array, and an array with rank greter than one is ealled a mult- dimensional array ach dimension ofan array ha an associated length which san integral number greater than or equal to zero, The dimension lengths are not part af the type af the array, but rather are ¢stablished when an instance ofthe array types cested at run-time, Te length of a dimen- sion determines the valid range of indies for that dimension; Fora dimension of length N, indies ean range from Oto N 1 inclusive, The otal number of elements in an aray isthe ‘product ofthe lengths ofeach dimension in the array. [Fone or moe ofthe dimensions ofan array havea length ora, the array i aid o be empty Theclement ype fe array canbe any ype, it ean be an array aia. In Caray are zero indeed; thai, the aray indexes star at zr. Arrays are mainly used to ee some values in 4 partialr order rays & Stings er 0 Declaring an Array Ct you bavetn dcae an aray yung anew Keywor, Fr exam declare an nor sing lato declare an arty net) ineare = new int (20): ‘his aray contin theelements fom tar) tints) Thenew operator ed crete theareay andl terry elements tr deft valucy Int eamoa ney lenent are ited ose. ‘The tps ined inthe previo example an array type Ara yes are wien wing ‘umarray-ipe fllmed by one cr mae rank species Folloneg empl howe vest Jacl varie declarations tt se ray pes wth int eth lament pe |S Seamer ne hrbondadealameaanieleteeros [clase Tose c finely aty 17 single-dimensional array of int ntl] ap 17 2eaimensiona array of iat AMt(.,) a3 77 3-aimensional arcey of int Anc(D1) 32:17 *Jaggea" array: array of tarcay of int} inet) 00 $32 Mf acray of larcay of (arcay of int) , ‘Arrays are reference types, ands the declaration of an srry variable merely sets sie pace forthe reference to the array. Array instanes are actually crested via uray initializes and ‘array creation expression. Fllowng example shows a varietyof array creation expressions c static void Main ¢ intl) at = new nett (ty 28g Ants} a2» new inti} (1. 2,53), (4, 5, 6)) Sne(,,1 a+ new inti0, 20, 30); inet $2 2 new ine); 3210) = pew tne (2, 2, 3); HOI = new int, 203, 4, 8, 6) 3212) = new intl) (2, 209) 40) 6, 4, 8, oly s Magic of C# With Net FrameWork ‘The variables al, a2 and a8 denote rectangular array, and the variable j2 denotes jas ‘array. It should beno surprise that these terms are based onthe shapes of tn arrays, Rectan ‘Bar arrays always have a rectangular shape. Given the length of ach dimension ofthe srry, ite rectangular shape is lear. For example, the length of i's three dimensions are 10,2, nd ‘80 respectively, and iis easy to ee tha this array contains 10°20°20 as elements, In contrast, the variable j2 denotes "jggod” array, or an “array of array. Specifically, 2 denotes an array of an array of int, o a sngle- dimensional srry of type intl. Each of those {nc variables canbe initialized individually, and this allows the array ta take on aged shape. The example gives each ofthe nt arrays a diffrent length. Speifally, the length of 4201 ie 3, the length of 2] 6, and the length of 22s. Ttisimportant to note thet the element type and number f dimensions are pars ofan aray’s ‘ype, but thatthe length ofeach dimension isnot part of the arrays type. This split ie made ‘lear inthe language syntax, as the length ofeach dimension is specified in the areay creation ‘expression rather than nthe array type. For inatanor, the declaration inl.,} a3 = new ine(20, 20, 301 ‘bas an array typeof intl) and an array creation expression of new int(10,20, 30, For local variable and fel declarations, a shorthand form is permite oa tht iis not nocee- ‘sary to restate the array type as shown below. ant{)oali= new inti) (1, 2, 344 Array Initialization ora single dimensional array, the array initilier must consist of a sequence of expressions ‘that are assignment compatible ith the element typeof the array. The expression initialize ‘array elements in inreasing order, starting with the element at index zero. The number af ‘expressions inthe array initialize determines the length ofthe aray instance being created Forexample, the array initializer above creates ann instanceelngth and then nities ‘the instance withthe allowing values: a0) © 0; ef) = 2; ata) = 4; 013) = 6: aft) = 8 Fora multidimensional array, the array iniilizr must have as many levels of nesting 26 ‘there are dimensions inthe array. The outermost nesting level corresponds ta the leftmost ‘mension and the innermost nesting level corresponds to therightmost dimension Th ongth ‘tench dimension ofthe array is determined bythe number of elemeats a the oeesponding ‘eating level in the array initializer. For cach nested array initializer, the number of elements ‘Bunt be the sme asthe other array inializes atthe same evel. For example, fnt{,) B= (G1. 5). (20, 25), (20, 25), (20, 281, (40, 451) CO ‘rae 8 Sings ‘ rates wedineasnal ara ith legate eins dimension and eng ‘0 for the rightmost dimension: 7 fot] bia new iets, a1 nd then ntalies the array instance with he lowing values: t BIO, OF + ay BID, a= bin, 0) © 20; Bid, 1) = As BID, 0} 290; Bia, t= bid, oF = 40; bia, 1H When an array creation expression inclades bth epic dimension lengths ad am aay Initialise, the lengths mast be constant expressra andthe number olmak {ng eel must match the correponding dimension length as shown below t fnc(] x = new Snet9) (0. 1, 20 ox Smet) = mew $mE13) 10, 1, 2. 30r ‘ere, the inital fory in eror bonus the dnennion enh expression nat const, andthe initialize fre sinerorbacause the length and the amber ef eements inthe initials beaten Passing Arrays as Parameters } Youcan pss. inihind aay method. Fo example: ‘You can ale iniiie and pam anew aray inane stp. For example: rethodinew int{] (1, 5, 10, 15, 20, 25, 20, 25, 40, 451) Example Inthe flowing example, string array i initialized at declaration time nd element are aplaedin a for op. bole public static void maint) Magic of C¥ With Net FrameWork c stringt) anes stringIS]("Shibs", “Robert, "Mathews", “Sofa”, “Ruby") Lortint {a0;4e57S00) ‘ Condole.WeiteLine( ‘Hello CH from (0)*,nanes{t]}2 ) fieiio ch from Shibi Helio CF tron Robert Helio # from Mathews Helio c# from sofia Mello ch from Raby ‘Example ‘This example builds an array, myArray, whose elements are array. Each ofthe array elements ‘haw diferent size 77 Reray of xrays using system: public clase ArrayTest c public static void maint) ‘ 1) peclaze the array of two elements: fine ()Clayarray = new int(2}(0: J/ tnstialize the elenents: yareay(0} = new nt(10} (1,5,10,15,20,25,30.35, 40,45); fmyarray(1) = new ine{3)(2,3,6,9.2217 77 Display the array elenents: for (int 10) 4 < 21 tee) ‘ i Console. Write (“Element ((0)): *, ths for (int $s07 J < myarray(i)-Uenothi 36+) Cconsote.Write(*40} *, mykeray(il(3117 Console, Weitetine(: Blenent (0): 1 § 10 15 20 25 30 35 a0 ¢s, Rlenent(2):13.6 9:32 Example [Now we see an example of «twodlimensina array where we intalize and pati tthe ‘nyhethd method where tselements ar dsplayed. The satis simar to what we ave for a ingle dimension aay 77 fwo-Ginencional acrays using systen; public class ArreyClass ( static void matethodtint{,) ) * 1/ Display the array elenents: for (ine 20; {= 4 dea) for (int J-0: 5 <2: de) Console. WriteLine(*Elenent ((0),{2))=421". 5, 3. wea) d public static void uain() 1/ tags the azray as a paraneter: myMethodinew int (,)((2,5) , (20,18) d (20,25) (90,38) + 40,45) 14 Output Blonent(0, 01-1 Element (0,1)+5 Etonent (1,0)-10 Element (1,1) 15 Elenent (2,0)-20 Element (2,1) 25 Element (3,0)-30 Element (3,1) =35 Elenent(4,0)-40 Blement (4,1)-45 fe hope you aro clear with the concept of multi-dimensional array. Let us try to write a two dimensional array which can hol sx elements. ‘Yea! that willbe as fellows: ‘string{.) sanew string{2] (312 ‘This is «two dimensional array with sie of 2x36, Le. itean hold sx objects. ‘This array can be initialized as String{,] senew string(2)(3]((*shibi*,“Robert*), (*Ruby*, Mathew"), ("Sanjeev", *Rahul*)) hibr | Robert | maby | sathew [1 Eager | ert]? Here s{1}[1] will be “mathew ‘Try the program below. ang Syston public class Arrayex ¢ ee ee eee ES ey Dublic static void Main) ‘ String.) namesenew stringi2] [31 ((*shib: (omuby" Mathew"), (*Sanjeev", “Rahul")) for(int 4-0:4<2:4++) ‘ obese), for(int j-01J<375+0 c Console. Writetine(*Hlelto C# from (0)*,nanea(i1(3)12 ‘Like this, you can define n dimensional arrays as string. sstringll_.n Using Out Like all out parameters, an out parameter ofan array type mist be assigned before it is used ‘hatin it must be assigned by the caller. When we use “out” in passing to our methods we are referring to actual variable in our methods 9 that whatever changes are made to that variable they are reflected in our main program. For example, public static vold wywechodvout inti] intare) ( intare = new int{i0]; // definite assignment of intarr , ‘The following example demonstrates the difference between out when weed pasting arrays tomethods. Example ‘in this example, the array intar is declared ia the caller (the Main method), and initialized in the FillArray method. Then, the array elements are returned to the caller and displayed, 77 Tsing out to pass the array to a method ‘using system class Testout ee ee Magic of C# Wih Net FrameWork ‘static public void FAliArray(out ine(]inearr) ‘ 1) toittalize the array: Sntare = new int(20} (1, , 20, 25, 20, 25, 30, 35, 40, > static public void main() ‘ ane{)sntarr; // Initialization ie not required 45h J/ vase the array to the caller using out PilaArray(out intare) ; Console.Writeline(*Array elenente are:*)s for (int ia) 1 < dntare-tength: i++) ‘Console. WriteLine(intarr [11)2 Output Array elements are: 1s 30 0 4 Strings in C# ‘Syntax newstring ~ new ateing((*stringLiteral*}) ‘Arrays & Strings ee a. a Arguments newString Required. The variable name to which the String object is assigned. a Optional. Any group of Unicode characters, Ct supports two forms of string literals: regular string literals and verbatim string literals. A regular string literal consist of zero or more characters enclosed in double quotes, a in “Hello, ‘world, and may include both simple escape sequences (such as \t forthe tab character) and Ihexadecimal escape sequences. ‘A verbatim string literal consists of an @ character followed by a double-quote character, 20 formore characters, and a closing double-quote character. A simple example is @"Hello, worl”. Ina verbatim string literal, the characters between the delimiters are interpreted verbatim, with the only exception being a quote eseape sequence. In particular, simple escape sequences land hexadecimal escape sequences are not processed in verbatim string literals. A verbatim. string literal may span multiple lines Example fering «= “hello, world” 77 wells, world string b = @*hello, world” 1/ hello, world string c = ‘hello \t world"; 17 belle world string d - @*nelle \t world’ 17 nelio \t world string © + ‘oe said \rilello\* to met; // Joe said “Hello string £ - @-doe said **Hellot* to mer; // Joe said “Hello” tring g = “\\\\sever\\ehare\\file.txt"; // \\server\share\file.txt string h = @*\\server\share\file.txt"; // \\server\share\File,txt string 4 - ‘one\ntwo\nthree* string j.+ @tone two three’: ‘The above example shows a variety of string literals. The last string literal, js a verbatim, Teing tral Ghat spans multiple lines. The characters between the quotation marks inluding Shite space such as newline characters, are duplicated verbatim. ‘Let us have a look at some methods which willbe constantly useful in programming, Sage «08 Wn Nae ‘These are the static methods of the class String Compare Coneat Equals Soin ‘This method will compare two Strings. Usage: Int i-Compare (strings. etring #2); I i=0, Strings are qual If i <0, sh <2; 1f O.st>s2; Coneatenates one oF more instances of String, or the String ‘representations of the values of one or more instances of Object. Usage: string «-Concattrng #1 string #2/!Concat two strings. string ‘S=Coneatiparams string!}/iConeat string aray. The same way you can caneatebjects ‘Creates new instanceof String with the same value asa specified {instanceof String Usage: string s=Copystring string #2), Determines whether tw String objects have the same value. int ‘sEqualsstring sl string 2) Concatenatcs a specified separator String between each element tf specified Sring arr. yielding a single concatenated string- ‘One very usefl instance of string property is Length. This returns the number of charactors this instance. int is Length wil give the length ofthe string. Let us have a look at some important instance methods of tring. Public Instance Methods Compares CopyTo EndsWith Baguals GetBnumerator Indexot Insert Compare this instance with a specie object. Copies a specified number af characters from «specified pa {Genin this instance toa specified position in an array of Unicode character, ‘Determines whether the end ofthis instance matches the speci fed String. ‘Determines whether two String objects have the same values, Fetrieves an object that canterate through the individual char acter inthis instance. ‘Reports the index ofthe first eccurrence ofa String, oF one oF ‘moe characters, within this instance. Inserts specified instance of String a specified index post tion inthis instance ‘Arrays & Stings o Lastindexor ‘Overloaded. Reports the index position of the last occurrence af ‘ specified Unicode character or String within this instance. PadLett [Right -alins the charactors in this instance, padding on the left ‘with spaces ora specified Unicode character fora specified tata length. PadRight Left-aligns the characters inthis string, padding on the right with spaces ora specified Unicode character, fora specified to- tal length, Remove Deletes a specified numberof characters frm this instance be- ‘ginning at a specitied position. Replace Roplaces all occurrences of a specified Unicode character or String in this instance, with another specified Unicode charac. ‘ter or String. split dentifies the substrings in this instance that are delimited by ‘one or more characters specified in an array, then paces the ‘substrings into a String array StartaWith Determines whether the heginning ofthis instance matches the specified String, Substring [Retrieves a substring from this instance ‘ToCharArray Copies the characters in this instance to a Unicode character array. ‘ToLower ‘Returns a copy ofthis String in lowercase. ‘ToString Overridden. Converts the value of this instance toa String. ‘ToUpper Returns a copy ofthis String in uppercase, Trim Removes all occurrences ofa set of specified characters from the beginning and end ofthis instance. String objects can be created implicitly using string literals String objects created in thi fash- fon referred toas standard string) are treated differently than String objects created using the ‘ew operator. All string literals share common, global string object. Ifa property is added to {string literal, iis availabe wo all standard string object. Vaz alpha, beter aipha = "Thi ie a steing “7 beta = "this is also a string *; Jalpha.test = 10: In the previous example, testis now defined for beta and all future string literals, In the follow ‘ng example, however, added properties are treated differently. [var gamma, delta; ganna ~ new string (This is a string *) delta = new string (*Thie is also a string *) jganma.test = 10; In this case, tes is not defined for delta. Bach object declared as a new object has its own set of ‘members. This isthe only ease where objects and literals are handled differently. String Indexing ‘The string class implements an indexer that allows the individual characters ofa string to be accessed. The indexer ofthe string class has the following declaration public char this(int index) (get: In other words, a read-only indexer takes a single argument of type int and returns an element of type char. Values passed for the index argument must be greater than or equal to zero and less than the length ofthe string. StringBuilder ‘The String object is immutable. Bvery time you use one ofthe methods in the System.String class, you create a new string object, In situations where you need to perform repeated modii- ‘ations toa string, the overhead associated with creating a new String object can be costly. The System/Text StringBuilder class can be used when you want to modify a string without creating a new object. ‘You can create a new instance ofthe StringBuilder object hy initializing your variable with ‘one of the overloaded constructor methods, illustrated inthe following code example: StringBuilder MyStringbuilder ~ new StringBuilder (“Hello Wor}d!*)s “Although the StringBuilder objet isa dynamic objet that allows you to expand the number ‘itheraters in the string that it encapsulates, you can specify vale fr the maximum number Sf characters that it can hold. This vale is called the capacity ofthe object and should not be actus with the length ofthe string thatthe current StringBuilder objet holds For example, Seu might create» ne instance ofthe StringBuilder clas with the string Hell" that has ewer my Jeng ofS and you might psi that the objet has mai maximum apacy 10 Yousan the capaci ofthe StringBuilder das wring oe ofthe verimdedcontrcors The long code example specifies thatthe My StringBuilder she canbe expanded uplos xine 28 spaces StringBulider Mystringauiiéer Additionally, you can use the read/write Capacity property to set the maximum length of 1e maximum length of your ‘object. Mhe following code example uses the Capacity property to define the maximum abject ‘MyStringBuilder Capacity lew StringBuilder (*Hello World!*, 25); Any attempt to expand the StringBuilder class beyond the maximum range throws ‘ArgumentOutOrRangeException ‘You can use the MaxCapactty property to retrieve the maximum capacity to which your StringBuilder object can possibly be expanded. You can never exceed this valve, as itis deter- ‘mined by the amount of free memory on your system. ‘The EnsureCapacity method ean be used to check the capacity of the current StringBuilder lass I'the eapacity is greater than the pasced value, nochange is made; however, ifthe eapac- ityisemaller than the passed value, the current capacity is changed to match the passed value. ‘The Length property can also be viewed or set Ifyou set the length property to a value that is ‘greater than the Capacity property, the capacity property is automaticaly changed to the ‘Same value as the length property. Setting the length property toa value that is les than the ength of the string within the current StringBuilder object shortens the string Manipulating the StringBuilder String ‘You can ws the fllowing methods to modify the contents ofthe StringBuilder object ‘Method Name Use StringBuilder Append Appends information tothe end of the current StringBuilder object. StringBuilder Insert Inserts a string or object into the specified index of ‘the current StringBuilder object. StringBuilder-Remove [Removes a specified number of indexes from the ‘current StringBuilder object, 2 Magic of C# Vit Not Frain StringBuilder Replace Replaces a specified index or character with the passed character. Append ‘The Append method can be used to add text or an object to the end ofthe string that exists inside the current StringBuilder Object. The following code example initializes a StringBuilder object to “Hello World” and then appends some text to the end of the StringBuilder object. StringBuilder MyStringBuilder = new StringBuilder ("Helle Worlai"); MystringBuilder-Append(* And anyone else who cares.*); Console WriteLine MystringBuilder) ; ‘This example displays ello World! And anyone else who cares. to the console AppendFormat “The AppendFormat method adds tet to the end ofthe StringBuilder object. It lo imple Trust he lPormattableintrfce and thereoreaceps the tandard format string desrbed Fe tag ac Te Glos td aie carina variable aad pend those walore toa StringBuilder ebect. Te following code example ute the serrenalFormnt method to pace en integer vale formated ax ncrreney valve a the endef 1 BlringBuilder cas. ine mytne = BS StringBuilder wyStringbuilder = new stringDvider(-Your total. ts 7) tysteingputlder,appendrornat (“(0:c) *, /EOE) 1 Console eitebinetivatringeuilder): ‘This example displays Your total is $25.00 tothe console. Insert abject The following coe example uses this method tosers a wora ine mae rn ‘StringBuilder lass Arrays & Stings 101 Stringbuilder wyStringuuilaer - new Seringbullder "Hello Worlai")P MyStringBulléer.tnsert 6, "Cruel “17 [console.triteLine (yStringBuiider! ‘This example displays He110 Cruel World! tothe console Remove ‘You can use the Remove method to remove a specified numberof characters frm the current StringBullder objec, boginning ata specified nero-based inden. The fallowing code example uses the Remove mothod to shorten a StringBuilder object, Stringbulider wyseringuslider = naw Seringhallder( Hello WoraT"TP uyseringBuiider Remove (5,7) [console.WriteLine (MyStringBuilder} ; ‘This example displays e110 tothe console, Replace ‘The Replace method can be used to replace either a specified character or a specified index location within the StringBuilder object with a passed character This example uses the Re- pplacemethod to search a StringBuilder object forall instances ofthe exclamation point char ‘eter (1) and replace them with the question mark character () Btrinabullder systringbullday ~ new Stvinghuilder (‘ello worldl*)y MyStringBuilder.Replace('!", °2); Console. WeiteLine MyStringsuilder) ‘This example displays e110 vor? tothe console, Refresh ‘This chepter covers, the uses of arrays and string in C#. Arrays play avery important ole in developing the application, Ifyou are a programmer you might have come acros situations hal tho object ina sequential manner and use tater. Whe you make an aray you mt ‘provide the sizeof the array. You must know how many objects you are going to store in a ray. As you have seen arrays can basicaly bo divided as single dimensional and multi ‘mensional. The correet usage of multi-dimensional arrays can solve many problems while

You might also like