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

Chapter 10.  Strings and Regular Expressions

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

Inthischapter,youwilllearntoworkwiththeC#stringtype

andthe.NETFrameworkSystem.Stringclassthatitaliases.

Youwillseehowtoextractsubstrings,manipulateand

concatenatestrings,andbuildnewstringswiththe

StringBuilderclass.Inaddition,youwilllearnhowtousethe

RegExclasstomatchstringsbasedoncomplexregular

expressions.



10.1.Strings

C#treatsstringsasfirst-classtypesthatareflexible,powerful,

andeasytouse.



InC#programmingyoutypicallyusetheC#aliasforaFramework

type(e.g.,intforInt32)butyouarealwaysfreetousetheunderlying

type.C#programmersthususestring(lowercase)andtheunderlying

FrameworktypeString(uppercase)interchangeably.



ThedeclarationoftheStringclassis:

publicsealedclassString:

IComparable,ICloneable,IConvertible,IEnumerable



Thisdeclarationrevealsthattheclassissealed,meaningthatit

isnotpossibletoderivefromtheStringclass.Theclassalso

implementsfoursysteminterfacesIComparable,

ICloneable,IConvertible,andIEnumerablethatdictate

functionalitythatStringshareswithotherclassesinthe.NET

Framework.



EachstringobjectisanimmutablesequenceofUnicodecharacters.

ThefactthatStringisimmutablemeansthatmethodsthatappearto

changethestringactuallyreturnamodifiedcopy;theoriginalstring

remainsintactinmemoryuntilitisgarbage-collected.Thismayhave

performanceimplications;ifyouplantodosignificantrepeatedstring

manipulation,useaStringBuilder(describedlater).



AsseeninChapter9,theIComparableinterfaceis

implementedbytypeswhosevaluescanbeordered.Strings,

forexample,canbealphabetized;anygivenstringcanbe

comparedwithanotherstringtodeterminewhichshouldcome

firstinanorderedlist.[1]IComparableclassesimplementthe

CompareTomethod.IEnumerable,alsodiscussedinChapter9,

letsyouusetheforeachconstructtoenumerateastringasa

collectionofchars.

[1]Orderingthestringisoneofanumberoflexicaloperationsthatactonthevalueofthestringandtakeinto

accountculture-specificinformationbasedontheexplicitlydeclaredcultureortheimplicitcurrentculture.



Compare



Therefore,ifthecurrentcultureisU.S.English(asisassumedthroughoutthisbook),the



a



A CompareOrdinalperformsanordinalcomparison,andthus

regardlessofculture,'a'isgreaterthan'A'.

methodconsiders' 'lessthan' '.



ICloneableobjectscancreatenewinstanceswiththesame

valueastheoriginalinstance.Inthiscase,itispossibletoclone

astringtoproduceanewstringwiththesamevalues

(characters)astheoriginal.ICloneableclassesimplementthe

Clone()method.



Actually,becausestringsareimmutable,theClone()methodon

Stringjustreturnsareferencetotheoriginalstring.Ifyouchangethe

clonedstring,anewStringisthencreated:



strings1="OneTwoThreeFour";

stringsx=(string)s1.Clone();

Console.WriteLine(

Object.ReferenceEquals(s1,sx));

sx+="Five";

Console.WriteLine(



Object.ReferenceEquals(s1,sx));

Console.WriteLine(sx);



Inthiscase,sxiscreatedasacloneofs1.ThefirstWriteLine

statementwillprintthewordTRue;thetwostringsvariablesreferto

thesamestringinmemory.Whenyouchangesxyouactuallycreatea

newstringfromthefirst,andwhentheReferenceEqualsmethod

returnsfalse,thefinalWriteLinestatementreturnsthecontentsofthe

originalstringwiththeword"Five"appended.



IConvertibleclassesprovidemethodstofacilitateconversion

tootherprimitivetypessuchasToInt32(),ToDouble(),

ToDecimal(),etc.



10.1.1.CreatingStrings

Themostcommonwaytocreateastringistoassignaquoted

stringofcharacters,knownasastringliteral,toauser-defined

variableoftypestring:

stringnewString="Thisisastringliteral";



Quotedstringscanincludeescapecharacters,suchas\nor\t,

whichbeginwithabackslashcharacter(\).Thetwoshownare

usedtoindicatewherelinebreaksortabsaretoappear,

respectively.



Becausethebackslashistheescapecharacter,ifyouwanttoputa

backslashintoastring(e.g.,tocreateapathlisting),youmustquote

thebackslashwithasecondbackslash(\\).



Stringscanalsobecreatedusingverbatimstringliterals,which

startwiththe(@)symbol.ThistellstheStringconstructorthat

thestringshouldbeusedverbatim,evenifitspansmultiple

linesorincludesescapecharacters.Inaverbatimstringliteral,

backslashesandthecharactersthatfollowthemaresimply

consideredadditionalcharactersofthestring.Thus,the

followingtwodefinitionsareequivalent:



stringliteralOne="\\\\MySystem\\MyDirectory\\ProgrammingC#.c

stringverbatimLiteralOne=

@"\\MySystem\MyDirectory\ProgrammingC#.cs";



Inthefirstline,anonverbatimstringliteralisused,andsothe

backslashcharacter(\)mustbeescaped.Thismeansitmust

beprecededbyasecondbackslashcharacter.Inthesecond

line,averbatimliteralstringisused,sotheextrabackslashis

notneeded.Asecondexampleillustratesmultilineverbatim

strings:

stringliteralTwo="LineOne\nLineTwo";

stringverbatimLiteralTwo=@"LineOne

LineTwo";



Ifyouhavedoublequoteswithinaverbatimstring,youmustescape

themsothatthecompilerknowswhentheverbatimstringends.



Again,thesedeclarationsareinterchangeable.Whichoneyou



useisamatterofconvenienceandpersonalstyle.



10.1.2.TheToString()Method

AnothercommonwaytocreateastringistocalltheToString(

)methodonanobjectandassigntheresulttoastringvariable.

Allthebuilt-intypesoverridethismethodtosimplifythetaskof

convertingavalue(oftenanumericvalue)toastring

representationofthatvalue.Inthefollowingexample,the

ToString()methodofanintegertypeiscalledtostoreits

valueinastring:

intmyInteger=5;

stringintegerString=myInteger.ToString();



ThecalltomyInteger.ToString()returnsaStringobject,

whichisthenassignedtointegerString.

The.NETStringclassprovidesawealthofoverloaded

constructorsthatsupportavarietyoftechniquesforassigning

stringvaluestostringtypes.Someoftheseconstructors

enableyoutocreateastringbypassinginacharacterarrayor

characterpointer.Passinginacharacterarrayasaparameterto

theconstructoroftheStringcreatesaCLR-compliantnew

instanceofastring.Passinginacharacterpointerrequiresthe

unsafemarkerasexplainedinChapter22.



10.1.3.ManipulatingStrings

Thestringclassprovidesahostofmethodsforcomparing,

searching,andmanipulatingstrings,themostimportantof

whichareshowninTable10-1.



Table10-1.Methodsandfieldsforthestringclass

Methodorfield



Purpose



Empty



Publicstaticfieldthatrepresentstheemptystring.



Compare()



Overloadedpublicstaticmethodthatcomparestwostrings.



CompareOrdinal( Overloadedpublicstaticmethodthatcomparestwostringswithout

)

regardtolocaleorculture.



Concat()



Overloadedpublicstaticmethodthatcreatesanewstringfromoneor

morestrings.



Copy()



Publicstaticmethodthatcreatesanewstringbycopyinganother.



Equals()



Overloadedpublicstaticandinstancemethodthatdeterminesiftwo

stringshavethesamevalue.



Format()



Overloadedpublicstaticmethodthatformatsastringusingaformat

specification.



Join()



Overloadedpublicstaticmethodthatconcatenatesaspecifiedstring

betweeneachelementofastringarray.



Chars



Thestringindexer.



Length



Thenumberofcharactersintheinstance.



CompareTo()



Comparesthisstringwithanother.



CopyTo()



CopiesthespecifiednumberofcharacterstoanarrayofUnicode

characters.



EndsWith()



Indicateswhetherthespecifiedstringmatchestheendofthisstring.



Equals()



Determinesiftwostringshavethesamevalue.



Insert()



Returnsanewstringwiththespecifiedstringinserted.



LastIndexOf() Reportstheindexofthelastoccurrenceofaspecifiedcharacterorstring

withinthestring.



PadLeft()



Right-alignsthecharactersinthestring,paddingtotheleftwithspaces

oraspecifiedcharacter.



PadRight()



Left-alignsthecharactersinthestring,paddingtotherightwithspaces

oraspecifiedcharacter.



Remove()



Deletesthespecifiednumberofcharacters.



Split()



Returnsthesubstringsdelimitedbythespecifiedcharactersinastring

array.



StartsWith()



Indicatesifthestringstartswiththespecifiedcharacters.



Substring()



Retrievesasubstring.



ToCharArray() Copiesthecharactersfromthestringtoacharacterarray.

ToLower()



Returnsacopyofthestringinlowercase.



ToUpper()



Returnsacopyofthestringinuppercase.



trim()



Removesalloccurrencesofasetofspecifiedcharactersfrombeginning

andendofthestring.



trimEnd()



BehaveslikeTRim(),butonlyattheend.



TRimStart()



BehaveslikeTRim(),butonlyatthestart.



Example10-1illustratestheuseofsomeofthesemethods,

includingCompare(),Concat()(andtheoverloaded+

operator),Copy()(andthe=operator),Insert(),EndsWith(

),andIndexOf().



Example10-1.Workingwithstrings

#regionUsingdirectives

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Text;

#endregion

namespaceWorkingWithStrings

{

publicclassStringTester

{

staticvoidMain()

{

//createsomestringstoworkwith

strings1="abcd";

strings2="ABCD";

strings3=@"LibertyAssociates,Inc.

providescustom.NETdevelopment,

on-siteTrainingandConsulting";

intresult;//holdtheresultsofcomparisons

//comparetwostrings,casesensitive

result=string.Compare(s1,s2);

Console.WriteLine(

"compares1:{0},s2:{1},result:{2}\n",

s1,s2,result);

//overloadedcompare,takesboolean"ignorecase"

//(true=ignorecase)

result=string.Compare(s1,s2,true);

Console.WriteLine("compareinsensitive\n");

Console.WriteLine("s4:{0},s2:{1},result:{2}\n",



s1,s2,result);

//concatenationmethod

strings6=string.Concat(s1,s2);

Console.WriteLine(

"s6concatenatedfroms1ands2:{0}",s6);

//usetheoverloadedoperator

strings7=s1+s2;

Console.WriteLine(

"s7concatenatedfroms1+s2:{0}",s7);

//thestringcopymethod

strings8=string.Copy(s7);

Console.WriteLine(

"s8copiedfroms7:{0}",s8);

//usetheoverloadedoperator

strings9=s8;

Console.WriteLine("s9=s8:{0}",s9);

//threewaystocompare.

Console.WriteLine(

"\nDoess9.Equals(s8)?:{0}",

s9.Equals(s8));

Console.WriteLine(

"DoesEquals(s9,s8)?:{0}",

string.Equals(s9,s8));

Console.WriteLine(

"Doess9==s8?:{0}",s9==s8);

//Twousefulproperties:theindexandthelength

Console.WriteLine(

"\nStrings9is{0}characterslong.",

s9.Length);

Console.WriteLine(

"The5thcharacteris{1}\n",



s9.Length,s9[4]);



//testwhetherastringendswithasetofcharacters

Console.WriteLine("s3:{0}\nEndswithTraining?:{1}\n

s3,

s3.EndsWith("Training"));

Console.WriteLine(

"EndswithConsulting?:{0}",

s3.EndsWith("Consulting"));

//returntheindexofthesubstring

Console.WriteLine(

"\nThefirstoccurrenceofTraining");

Console.WriteLine("ins3is{0}\n",

s3.IndexOf("Training"));

//insertthewordexcellentbefore"training"

strings10=s3.Insert(101,"excellent");

Console.WriteLine("s10:{0}\n",s10);

//youcancombinethetwoasfollows:

strings11=s3.Insert(s3.IndexOf("Training"),

"excellent");

Console.WriteLine("s11:{0}\n",s11);

}

}

}

Output:

compares1:abcd,s2:ABCD,result:-1

compareinsensitive

s4:abcd,s2:ABCD,result:0

s6concatenatedfroms1ands2:abcdABCD

s7concatenatedfroms1+s2:abcdABCD



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

Chapter 10.  Strings and Regular Expressions

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

×