Your SlideShare is downloading. ×

Chapter5: Usage of Build-In Functions or Methods

448

Published on

មេរៀន Advance C# ជំពូកទី ៥ សំរាប់ក្រុម E1 & E2

មេរៀន Advance C# ជំពូកទី ៥ សំរាប់ក្រុម E1 & E2

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
448
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Advanced Programm d ming Method dology in C# # N Norton University  Usa of Buil age ld-In Funct F tions or Me ethod dsWorki with Charac ing h ctersThe built-in char ty represents a single Unicode c ype e character. Unicode is a widely use edstandard for encod d ding text. It supports nearly 200,00 different characters in 91 diffe 00 t s erentscripts. C# stores ea charact using tw bytes. Th char key C ach ter wo he yword is an alias to the eSystem.C Char struct. .Expres ssing Cha aracters Using LiteralsTo make using char easier, C# supports character lit e # c terals, an ex xample of w which is sho ownin Listing 16-1. gListing 16 A Character Literal 6-1.char my yChar = a; The statement in Li isting 16-1 uses a char racter literal to assign the lowerca a character aseto a char variable called myCh Charact literals a expresse between single quo har. ter are ed n otes, rated by Figas illustr gure 16-1.Some sp pecial chara acters canno be expre ot essed direct and so c tly, character lit terals can b beexpresse using an escape seq ed n quence or a Unicode e encoding. F example the single For e, equote ch haracter can nnot be exp pressed dire ectly since it is used to define oth characte o her erliterals. Listing 16-2 demonstrates how to express th characte using an escape L 2 o his ersequenc and a Un ce nicode enco oding. Pa 1 age
  • 2. Advanced Programm d ming Method dology in C# # N Norton University Listing 16-2. Expressing a Character Through an Escape Seque g E encechar my yEscapedQuote =  ; char my yUnicodeQuote =  u0027; char my yHexQuote = x002 27; Characte literal esc er cape seque ences start with a back w kslash chara acter () and can be a dsimple escape sequ e uence or a Unicode en U ncoding, exp pressed eith in decim (prefixe her mal edwith a u) or in hexa ) adecimal (prefixed with an x). Tab 16-2 sho some o the most h ble ows offrequent used cha tly aracter liter escape sequences. ral sUsing Struct Members MThe char keyword is an alias to the System.Char stru which c r o uct, contains a n number of s staticmethods to aid in working wit character The mos useful are described in Table 16 s w th rs. st e d 6-3. Pa 2 age
  • 3. Advanced Programm d ming Method dology in C# # N Norton University Using StringsA string object repr resents a re ead-only sequence of U Unicode ch haracters. Th string hekeyword is an alias for the Sys d stem.String class, and l like all the o other built- type alia -in ases,you can choose to use either the keyword or the cla name or switch bet t ass r tween them mfreely.Expres ssing Str rings Usin String Literals ng g sAs with the other C# built-in types, you can define s t C c string value using lite es erals, asdemonstrated by Listing 16-5. .Listing 16-5. Using a St tring Literalstring myString = "Intro oduction t to C#"; String lit terals are defined by placing a sequence of c p characters between a pair of dou ublequotes ("), as illustr ( rated by Fig gure 16-2. Pa 3 age
  • 4. Advanced Programm d ming Method dology in C# # N Norton University The statement in Li isting 16-5 uses a strin literal to create a string object with the va ng alueof “Intro oduction of C#” and as ssigns it to a string var riable called myString. dPerfor rming Op perations on Strings sThe follo owing sectio demon ons nstrate how to perform common operations on string mobjects.Comparing Strin ngsC# lets you compar strings directly using the comp y re parison ope erators (== and !=). Th hereis no nee to use a compariso method, such as the Java equa method. ed on e als .These op perators are case sens e sitive so tha the string Introduct at g tion is not t same as the the sstring in ntroduction n.Combin ning StringsStrings can be com c mbined using the addition operato (+) g or Pa 4 age
  • 5. Advanced Programm d ming Method dology in C# # N Norton University Reading Individu Charac ual ctersThe strin class imp ng plements an indexer th allows y to acce individual characters. n hat you essYou can’t use the in ndexer to modify the characters s m c since strings are read-only. Codebelow demonstrate using the indexer, along with the Length property, in a for loop to es e n penumera the contents of a string. ate sUsing Regular Expressi ionsYou can use regular expressions to search and manipulate strin using the ngsSystem.Text.Regul larExpressi ions.Regex class. Regular expres x ssions are an advanced dtopic, bu I have inc ut cluded a sim mple examp so that you know t feature exists. You can ple thefind deta of C# re ails egular expr ressions at the followin URL: t nghttp://m msdn.micros soft.com/en n-us/library/ /hs600312.aspx. Code below con e ntains anexample of using re e egular expr ressions to search strin ngs. Pa 5 age
  • 6. Advanced Programm d ming Method dology in C# # N Norton University This example searches a set of book titles for the te rm pro, loo f oking for matchesirrespect tive of case (that is, pr Pro, PRo and prO w e ro, o would all be considere matches). e edManip pulating StringsTable 16 describe the meth available for manipulating strings. As pr 6-4 es hod reviouslymention ned, string values are read-only, and so thos e methods that seem to edit the v r avalue of a string are in fact cre e eating new string value es. Pa 6 age
  • 7. Advanced Programming Methodology in C# d m d # Norton University  Pa 7 age
  • 8. Advanced Programm d ming Method dology in C# # N Norton University Code be elow contains a demon nstration of some of th f hese metho ods. Pa 8 age
  • 9. Advanced Programm d ming Method dology in C# # N Norton University The code above pro oduces the following results: rSearch hing Strin ngsThe strin class def ng fines severa methods to search s al strings.Code be elow contains a demon nstration of some of th f hese metho ods. Pa 9 age
  • 10. Advanced Programm d ming Method dology in C# # N Norton University The code above pro oduces the following results: rOther String Methods MTwo oth member of the str her rs ring class ar worth me re entioning b do not f into the but fitmanipulating or sea arching stri ings catego ories. elow contains a demonCode be nstration of some of th f hese metho ods. Pag 10 ge
  • 11. Advanced Programm d ming Method dology in C# # N Norton University The code above pro oduces the following results: rUsing the Stri ingBuild Class der sThe Strin ngBuilder class, contained in the System.Tex namespace, is the m xt mutablecompanion to the read-only string class. You can ed the cont r dit tents of a st tring nted by a Strepresen tringBuilder object and perform o d operations that are fas and mo ster oreefficient than worki with str ing rings directl The main use of the StringBuil ly. n e lder class is to sbuild str rings throug multiple append op gh e perations.Creating a Stri ingBuilde Object erThere is no equivalent to the string literal to define StringBuild values. Y must s der Youinstead use one of the class co onstructors, the simple of which has no pa est h arameters, likethis: Builder myStringB yBuilder = new Str ringBuilde er();  Pag 11 ge
  • 12. Advanced Programming Methodology in C# Norton University A StringBuilder object uses a char array to store the characters of the string itrepresents. This array will be resized as needed to accommodate the effect of building astring by adding characters.You can recommend an initial size of array for a StringBuilder object to allocate byproviding an int constructor parameter, like this:StringBuilder myBuilder = new StringBuilder(10); Suggesting an array capacity that is large enough to hold the string you intend to buildcan avoid the time-consuming operation of creating a larger array and copying thecontents of the StringBuilder to it.If you already have the foundation for the string that you want to build, you can providethis as the basis of the StringBuilder, like this:StringBuilder myBuilder = new StringBuilder("Introduction to"); Using a StringBuilder ObjectThe StringBuilder class includes a range of members that help you manipulate thecontents of strings. Page 12
  • 13. Advanced Programm d ming Method dology in C# # N Norton University Code be elow contains a demon nstration of some of th ese metho f h ods. Pag 13 ge
  • 14. Advanced Programm d ming Method dology in C# # N Norton University The code above pro oduces the following results: rUsing the Appen and Ins t nd sert Metho odsThe App pend and In nsert metho are the heart of the StringBuilder class. T ods e They allow y youto quick build stri kly ings by con ncatenating smaller str rings togeth and inse her ertingfragmen of string into large ones. nts gs er Pag 14 ge
  • 15. Advanced Programm d ming Method dology in C# # N Norton University The code above pro oduces the following results: rUsing the StringBuilder In t ndexerThe last point of no for the StringBuilde class is that you can read and modify ote S er ncharacte using a custom indexer. (By co ers c ontrast, you can only r u read charac cters using t theindexer implemented in the st tring class.)The code above pro oduces the following results: rForma atting St tringsC# has comprehensive suppor for forma c rt atting string through a feature called gscomposite formatti ing. The following sect tions demo onstrate how to use this feature to w oformat strings in a range of different way s ys.Using Compos Form site matting Pag 15 ge
  • 16. Advanced Programm d ming Method dology in C# # N Norton University The C# composite formatting feature will create a st c f tring repres sentation fo each object, orwhich is used to replace the co orresponding format i item.Code ab bove is basic composite formattin example.. The string that conta ng g ains the form matitems is illustrated below:A format item is wr rapped in brace charac b cters ({ and }) and are numbered from zeroonward. There are two format items cont t t tained in th string ass he signed to th formatSt he tring riable, numbered 0 and 1.local var dThe static Console.W WriteLine method sup m pports the c composite f formatting feature and will daccept a number of parameters. The first parameter to follow t string w be used for f r the willformat it tem zero, th next for format item one, and so on. he mFormat items don’t have to ap i t ppear in seq quence and can be use more than once. He d ed ereis an exa ample:The outp from th put hese statem ments is as fo ollows:London is the ho ome city of Adam. Adam is  38 years old. Escapin Braces ngIf you want to display brace ch haracters in a string th you will use for com n hat mpositeformatting, then yo must use an escape sequence.. Two open brace char ou e e racters ({{) w willbe interp preted as a single ope brace cha en aracter ({), a two clo brace ch and ose haracters (}})will be in nterpreted as a single close brace character (}). e Pag 16 ge
  • 17. Advanced Programm d ming Method dology in C# # N Norton University The code above pro oduces the following results: rForma atting Ty ypesWhen yo use com ou mposite form matting, you can specify any obje or value you want t u ect toinclude in the comp posited string. The com mposite for rmatting sy ystem create a string esrepresen ntation of th object or value by calling the T he o c ToString m method, whic is define in ch edSystem.O Object and so is inheri ited by all reference an value types. When you use r ndcomposite formatti ing, there are some op a ptions to co ontrol how an object o value is or nted as a string.represenUsing a Format Componen C ntA format component is an opt tional part of a format item that s o t specifies ho an objec or ow ctvalue should be dis splayed.The statement that contains th format it t he tem with th format co he omponent is shown in nbold. Pag 17 ge
  • 18. Advanced Programm d ming Method dology in C# # N Norton University A format component consists of a single character a an opti and ional nume value. The ericcharacte specifies the kind of formatting that should be applie and the numeric va er f g ed, e aluespecifies the precision. In the case of Listing 16-24, t format componen specifies that s c the ntthe fixed d-point form ould be use and that the prevision should b two decimal matting sho ed beplaces. The code ab T bove produ uces the foll lowing resu ults:Format component are availa c ts able for the built-in nu e umeric type and date and time estypes. Th most use numeri format co he eful ic omponents are describ in Table 16-8. s bedCode be elow demon nstrates how to use the format co w omponents in Table 16 s 6-8. Pag 18 ge
  • 19. Advanced Programm d ming Method dology in C# # Norton University Code ab bove produc the follo ces owing results: Pag 19 ge
  • 20. Advanced Programming Methodology in C# Norton University References:  Adam Freeman. (2010). Introduction Visual C# 2010. Page 20

×