Tải bản đầy đủ - 0 (trang)
Chapter 3. Strings and Regular Expressions

Chapter 3. Strings and Regular Expressions

Tải bản đầy đủ - 0trang

WorkingwithStrings

Beingabletoworkwithstringsisanessentialskillincreating

high-qualityapplications.Evenifyouareworkingwithnumeric

orimagedata,endusersneedtextualfeedback.Thissectionof

thechapterwillintroduceyouto.NETstrings,howtoformat

them,manipulatethemandcomparethem,aswellasother

usefuloperations.



Introductiontothe.NETString

Beforethe.NETFrameworkandtheCommonLanguage

Runtime(CLR),developersusedtohavetospendconsiderable

amountofeffortworkingwithstrings.Areusablelibraryof

stringroutineswasapartofvirtuallyeveryCandC++

programmer'stoolbox.Itwasalsodifficulttowritecodethat

exchangedstringdatabetweendifferentprogramming

languages.Forexample,Pascalstoresstringsasanin-memory

characterarray,wherethefirstelementofthearrayindicated

thelengthofthestring.Cstoresstringsasanin-memoryarray

ofcharacterswithavariablelength.Theendofthestringwas

indicatedbytheASCIInullcharacter(representedinCas\0).

Inthe.NETFramework,stringsarestoredasimmutablevalues.

ThismeansthatwhenyoucreateastringinC#(oranyother

.NETlanguage),thatstringisstoredinmemoryinafixedsize

tomakecertainaspectsoftheCLRrunfaster(youwilllearn

moreaboutthisinChapter16,"OptimizingYourNET2.0

Code").Asaresult,whenyoudothingssuchasconcatenate

stringsormodifyindividualcharactersinastring,theCLRis

actuallycreatingmultiplecopiesofyourstring.

StringsinC#aredeclaredinthesamewayasothervaluetypes

suchasintegerorfloat,asshowninthefollowingexamples:



stringx="HelloWorld";

stringy;

stringz=x;



FormattingStrings

Oneofthemostcommontaskswhenworkingwithstringsis

formattingthem.Whendisplayinginformationtousers,you

oftendisplaythingslikedates,times,numericvalues,decimal

values,monetaryvalues,oreventhingslikehexadecimal

numbers.C#stringsallhavetheabilitytodisplaythesetypes

ofinformationandmuchmore.Anotherpowerfulfeatureisthat

whenyouusethestandardformattingtools,theoutputofthe

formattingwillbelocalization-aware.Forexample,ifyou

displaythecurrentdateinshortformtoauserinEngland,the

currentdateinshortformwillappeardifferenttoauserinthe

UnitedStates.

Tocreateaformattedstring,allyouhavetodoisinvokethe

Formatmethodofthestringclassandpassitaformatstring,as

showninthefollowingcode:

stringformatted=string.Format("Thevalueis{0}",value);



The{0}placeholderindicateswhereavalueshouldbeinserted.

Inadditiontospecifyingwhereavalueshouldbeinserted,you

canalsospecifytheformatforthevalue.

Otherdatatypesalsosupportbeingconvertedintostringsvia

customformatspecifiers,suchastheDateTimedatatype,which

canproduceacustom-formattedoutputusing



DateTime.ToString("formatspecifiers");



Table3.1illustratessomeofthemostcommonlyusedformat

stringsforformattingdates,times,numericvalues,andmore.

Table3.1.CustomDateTimeFormatSpecifiers

Specifier



Description



d



Displaysthecurrentdayofthemonth.



dd



Displaysthecurrentdayofthemonth,wherevalues<

10havealeadingzero.



ddd



Displaysthethree-letterabbreviationofthenameof

thedayoftheweek.



dddd(+)



Displaysthefullnameofthedayoftheweek

representedbythegivenDateTimevalue.



f(+)



Displaysthexmostsignificantdigitsoftheseconds

value.Themoref'sintheformatspecifier,themore

significantdigits.Thisistotalseconds,notthenumber

ofsecondspassedsincethelastminute.



F(+)



Sameasf(+),excepttrailingzerosarenotdisplayed.



g



DisplaystheeraforagivenDateTime(forexample,

"A.D.")



h



Displaysthehour,inrange112.



hh



Displaysthehour,inrange112,wherevalues<10

havealeadingzero.



H



Displaysthehourinrange023.



HH



Displaysthehourinrange023,wherevalues<10have

aleadingzero.



m



Displaystheminute,range059.



mm



Displaystheminute,range059,wherevalues<10

havealeadingzero.



M



Displaysthemonthasavaluerangingfrom112.



MM



Displaysthemonthasavaluerangingfrom112where

values<10havealeadingzero.



MMM



Displaysthethree-characterabbreviatednameofthe

month.



MMMM



Displaysthefullnameofthemonth.



s



Displaysthenumberofsecondsinrange059.



ss(+)



Displaysthenumberofsecondsinrange059,where

values<10havealeading0.



t



DisplaysthefirstcharacteroftheAM/PMindicatorfor

thegiventime.



tt(+)



DisplaysthefullAM/PMindicatorforthegiventime.



y/yy/yyyy



Displaystheyearforthegiventime.



z/zz/zzz(+)



Displaysthetimezoneoffsetforthegiventime.



Takealookatthefollowinglinesofcode,whichdemonstrate

usingstringformatspecifierstocreatecustom-formatteddate

andtimestrings:

DateTimedt=DateTime.Now;



Console.WriteLine(string.Format("Defaultformat:{0}",dt.ToStr

Console.WriteLine(dt.ToString("ddddddMMMM,yyyyg"));



Console.WriteLine(string.Format("CustomFormat1:{0:MM/dd/yyh

Console.WriteLine(string.Format("CustomFormat2:{0:hh:mm:sstt



Hereistheoutputfromtheprecedingcode:

Defaultformat:9/24/200512:59:49PM

Saturday24September,2005A.D.

CustomFormat1:09/24/0512:59:49PM

CustomFormat2:12:59:49PMGMT-06



Youcanalsoprovidecustomformatspecifiersfornumeric

valuesaswell.Table3.2describesthecustomformatspecifiers

availablefornumericvalues.

Table3.2.NumericCustomFormatSpecifiers

Specifier



Description



0



Thezeroplaceholder.



#



Thedigitplaceholder.Ifthegivenvalue

hasadigitinthepositionindicatedbythe

#specifier,thatdigitisdisplayedinthe

formattedoutput.



.



Decimalpoint.



,



Thousandsseparator.



%



Percentagespecifier.Thevaluebeing

formattedwillbemultipliedby100before

beingincludedintheformattedoutput.



E0/E+0/e/e+0/e-0/E



Scientificnotation.



'XX'or"XX"



Literalstrings.Theseareincludedliterally



intheformattedoutputwithout

translationintheirrelativepositions.

;



Sectionseparatorforconditional

formattingofnegative,zero,andpositive

values.



Ifmultipleformatsectionsaredefined,conditionalbehaviorcan

beimplementedforevenmorefine-grainedcontrolofthe

numericformatting:

TwosectionsIfyouhavetwoformattingsections,thefirst

sectionappliestoallpositive(including0)values.The

secondsectionappliestonegativevalues.Thisisextremely

handywhenyouwanttoenclosenegativevaluesin

parenthesesasisdoneinmanyaccountingsoftware

packages.

ThreesectionsIfyouhavethreeformattingsections,the

firstsectionappliestoallpositive(notincluding0)values.

Thesecondsectionappliestonegativevalues,andthethird

sectionappliestozero.

Thefollowingfewlinesofcodeillustratehowtousecustom

numericformatspecifiers.

doubledVal=59.99;

doubledNeg=-569.99;

doublezeroVal=0.0;

doublepct=0.23;

stringformatString="{0:$#,###0.00;($#,###0.00);nuttin}";

Console.WriteLine(string.Format(formatString,dVal));

Console.WriteLine(string.Format(formatString,dNeg));

Console.WriteLine(string.Format(formatString,zeroVal));



Console.WriteLine(pct.ToString("00%"));



Theoutputgeneratedbytheprecedingcodeisshowninthe

followingcode:

$59.99

($569.99)

nuttin

23%



ManipulatingandComparingStrings

Inadditiontodisplayingstringsthatcontainallkindsof

formatteddata,othercommonstring-relatedtasksarestring

manipulationandcomparison.Animportantthingtokeepin

mindisthatthestringisactuallyaclassintheunderlyingBase

ClassLibraryofthe.NETFramework.Becauseitisaclass,you

canactuallyinvokemethodsonastring,justasyoucaninvoke

methodsonanyotherclass.

Youcaninvokethesemethodsbothonstringliteralsoron

stringvariables,asshowninthefollowingcode:

intx=string.Length();

inty="HelloWorld".Length();



Table3.3isashortlistofsomeofthemostcommonlyused

methodsthatyoucanuseonastringforobtaininginformation

aboutthestringormanipulatingit.



Table3.3.CommonlyUsedStringInstanceMethods

Method



Description



CompareTo



Comparesthisstringinstancewithanother

stringinstance.



Contains



ReturnsaBooleanindicatingwhetherthecurrent

stringinstancecontainsthegivensubstring.



CopyTo



Copiesasubstringfromwithinthestring

instancetoaspecifiedlocationwithinanarrayof

characters.



EndsWith



ReturnsaBooleanvalueindicatingwhetherthe

stringendswithagivensubstring.



Equals



Indicateswhetherthestringisequaltoanother

string.Youcanusethe'=='operatoraswell.



IndexOf



Returnstheindexofasubstringwithinthestring

instance.



IndexOfAny



Returnsthefirstindexoccurrenceofany

characterinthesubstringwithinthestring

instance.



PadLeft



Padsthestringwiththespecifiednumberof

spacesoranotherUnicodecharacter,effectively

right-justifyingthestring.



PadRight



Appendsaspecifiednumberofspacesorother

Unicodecharactertotheendofthestring,

creatingaleft-justification.



Remove



Deletesagivennumberofcharactersfromthe

string.



Replace



Replacesalloccurrencesofagivencharacteror

stringwithinthestringinstancewiththe

specifiedreplacement.



Split



Splitsthecurrentstringintoanarrayofstrings,

usingthespecifiedcharacterasthesplitting

point.



StartsWith



ReturnsaBooleanvalueindicatingwhetherthe

stringinstancestartswiththespecifiedstring.



SubString



Returnsaspecifiedportionofthestring,givena

startingpointandlength.



ToCharArray



Convertsthestringintoanarrayofcharacters.



ToLower



Convertsthestringintoalllowercasecharacters.



ToUpper



Convertsthestringintoalluppercasecharacters.



Trim



Removesalloccurrencesofagivensetof

charactersfromthebeginningandendofthe

string.



TrimStart



PerformstheTRimfunction,butonlyonthe

beginningofthestring.



TrimEnd



PerformstheTRimfunction,butonlyontheend

ofthestring.



Takealookatthefollowingcode,whichillustratessomeofthe

thingsyoucandowithstringstofurtherqueryandmanipulate

them:



stringsourceString="MaryHadaLittleLamb";

stringsourceString2="MaryHadaLittleLamb";

Console.WriteLine(sourceString.ToLower());

Console.WriteLine(string.Format("Thestring'{0}'is{1}chars

sourceString,sourceString.Length));

Console.WriteLine(string.Format("Fourthwordinsentenceis:{

sourceString.Split('')[3]));

Console.WriteLine(sourceString2.Trim());

Console.WriteLine("Twostringsequal?"+(sourceString==sour



Theoutputoftheprecedingcodelooksasfollows:

maryhadalittlelamb

Thestring'MaryHadaLittleLamb'is22charslong.

Fourthwordinsentenceis:Little

MaryHadaLittleLamb

Twostringsequal?True



IntroductiontotheStringBuilder

Asmentionedearlier,stringsareimmutable.Thismeansthat

whenyouconcatenatetwostringstoformathirdstring,there

willbeashortperiodoftimewheretheCLRwillactuallyhave

allthreestringsinmemory.So,forexample,whenyou

concatenateasshowninthefollowingcode:

stringa="Hello";

stringb="World";

stringc=a+""+c;



Youactuallyendupwithfourstringsinmemory,includingthe

space.Toalleviatethisperformanceissuewithstring

concatenationaswellastoprovideyouwithatooltomake

concatenationeasier,the.NETFrameworkcomeswithaclass

calledtheStringBuilder.

ByusingaStringBuildertodynamicallycreatestringsofvariable

length,yougetaroundtheimmutablestringfactofCLRstrings

andthecodecanoftenbecomemorereadableasaresult.Take

alookattheStringBuilderinactioninthefollowingcode:



StringBuildersb=newStringBuilder();

sb.Append("Greetings!\n");

formatString="{0:$#,###0.00;($#,###0.00);Zero}";

dVal=129.99;

sb.AppendFormat(formatString,dVal);

sb.Append("\nThisisabigconcatenatedstring.");

Console.WriteLine(sb.ToString());



Theoutputoftheprecedingcodelookslikethefollowing:

Greetings!

$129.99

Thisisabigconcatenatedstring.



Notethatthe\nfromtheprecedingcodeinsertsanewline

characterintothestring.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3. Strings and Regular Expressions

Tải bản đầy đủ ngay(0 tr)

×