Tải bản đầy đủ - 0 (trang)
Chapter 11. Character Strings and String Functions

Chapter 11. Character Strings and String Functions

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

RepresentingStringsandStringI/O

Ofcourse,youalreadyknowthemostbasicfact:Acharacter

stringisachararrayterminatedwithanullcharacter(\0).

Therefore,whatyou'velearnedaboutarraysandpointers

carriesovertocharacterstrings.Butbecausecharacterstrings

aresocommonlyused,Cprovidesmanyfunctionsspecifically

designedtoworkwithstrings.Thischapterdiscussesthenature

ofstrings,howtodeclareandinitializestrings,howtogetthem

intoandoutofprograms,andhowtomanipulatestrings.

Listing11.1presentsabusyprogramthatillustratesseveral

waystosetup,read,andprintstrings.Itusestwonew

functionsgets(),whichreadsastring,andputs(),whichprints

astring.(Youprobablynoticeafamilyresemblanceto

getchar()andputchar().)Therestoftheprogramshould

lookfairlyfamiliar.



Listing11.1.Thestrings.cProgram



//strings.c--stringingtheuseralong

#include

#defineMSG"Youmusthavemanytalents.Tellmesome."

//asymbolicstringconstant

#defineLIM5

#defineLINELEN81//maximumstringlength+1

intmain(void)



{

charname[LINELEN];

chartalents[LINELEN];

inti;

//initializingadimensioned

//chararray

constcharm1[40]="Limityourselftooneline'sworth.";

//lettingthecompilercomputethe

//arraysize



constcharm2[]="Ifyoucan'tthinkofanything,fakeit.

//initializingapointer

constchar*m3="\nEnoughaboutme--what'syourname?";

//initializinganarrayof

//stringpointers

constchar*mytal[LIM]={//arrayof5pointers

"Addingnumbersswiftly",

"Multiplyingaccurately","Stashingdata",

"Followinginstructionstotheletter",



"UnderstandingtheClanguage"

};



printf("Hi!I'mClydetheComputer."

"Ihavemanytalents.\n");

printf("Letmetellyousomeofthem.\n");

puts("Whatwerethey?Ah,yes,here'sapartiallist.");

for(i=0;i
puts(mytal[i]);//printlistofcomputertalents

puts(m3);

gets(name);

printf("Well,%s,%s\n",name,MSG);

printf("%s\n%s\n",m1,m2);

gets(talents);

puts("Let'sseeifI'vegotthatlist:");

puts(talents);

printf("Thanksfortheinformation,%s.\n",name);



return0;



}



Toshowyouwhatthisprogramdoes,hereisasamplerun:



Hi!I'mClydetheComputer.Ihavemanytalents.

Letmetellyousomeofthem.

Whatwerethey?Ah,yes,here'sapartiallist.

Addingnumbersswiftly

Multiplyingaccurately

Stashingdata

Followinginstructionstotheletter

UnderstandingtheClanguage



Enoughaboutmewhat'syourname?

NigelBarntwit



Well,NigelBarntwit,Youmusthavemanytalents.Tellmesome.

Justlimityourselftooneline'sworth.

Ifyoucan'tthinkofanything,fakeit.

Fencing,yodeling,malingering,cheesetasting,andsighing.

Let'sseeifI'vegotthatlist:

Fencing,yodeling,malingering,cheesetasting,andsighing.

Thanksfortheinformation,NigelBarntwit.



RatherthangoingthroughListing11.1line-by-line,let'stakea

moreencompassingapproach.First,youwilllookatwaysof

definingastringwithinaprogram.Thenyouwillseewhatis

involvedinreadingastringintoaprogram.Finally,youwill

studywaystooutputastring.



DefiningStringsWithinaProgram

AsyouprobablynoticedwhenyoureadListing11.1,thereare

manywaystodefineastring.Theprincipalwaysareusing

stringconstants,usingchararrays,usingcharpointers,and

usingarraysofcharacterstrings.Aprogramshouldmakesure

thereisaplacetostoreastring,andwewillcoverthattopic,

too.



CharacterStringConstants(StringLiterals)



Astringconstant,alsotermedastringliteral,isanything

enclosedindoublequotationmarks.Theenclosedcharacters,

plusaterminating\0characterautomaticallyprovidedbythe

compiler,arestoredinmemoryasacharacterstring.The

programusesseveralsuchcharacterstringconstants,most

oftenasargumentsfortheprintf()andputs()functions.

Note,too,thatyoucanuse#definetodefinecharacterstring

constants.

RecallthatANSICconcatenatesstringliteralsiftheyare

separatedbynothingorbywhitespace.Forexample,



chargreeting[50]="Hello,and""howare""you"

"today!";



isequivalenttothis:



chargreeting[50]="Hello,andhowareyoutoday!";



Ifyouwanttouseadoublequotationmarkwithinastring,

precedethequotationmarkwithabackslash,asfollows:



printf("\"Run,Spot,run!\"exclaimedDick.\n");



Thisproducesthefollowingoutput:



"Run,Spot,run!"exclaimedDick.



Characterstringconstantsareplacedinthestaticstorageclass,

whichmeansthatifyouuseastringconstantinafunction,the

stringisstoredjustonceandlastsforthedurationofthe

program,evenifthefunctioniscalledseveraltimes.Theentire

quotedphraseactsasapointertowherethestringisstored.

Thisactionisanalogoustothenameofanarrayactingasa



pointertothearray'slocation.Ifthisistrue,whatkindof

outputshouldtheprograminListing11.2produce?



Listing11.2.Thequotes.cProgram



/*quotes.c--stringsaspointers*/

#include

intmain(void)

{

printf("%s,%p,%c\n","We","are",*"spacefarers");



return0;

}



The%sformatshouldprintthestringWe.The%pformat

producesanaddress.Soifthephrase"are"isanaddress,then

%pshouldprinttheaddressofthefirstcharacterinthestring.

(Pre-ANSIimplementationsmighthavetouse%uor%luinstead

of%p.)Finally,*"spacefarers"shouldproducethevalueof

theaddresspointedto,whichshouldbethefirstcharacterof

thestring"spacefarers".Doesthisreallyhappen?Well,here

istheoutput:



We,0x0040c010,s



CharacterStringArraysandInitialization

Whenyoudefineacharacterstringarray,youmustletthe

compilerknowhowmuchspaceisneeded.Onewayisto

specifyanarraysizelargeenoughtoholdthestring.The

followingdeclarationinitializesthearraym1tothecharactersof

theindicatedstring:



constcharm1[40]="Limityourselftooneline'sworth.";



Theconstindicatestheintenttonotalterthisstring.

Thisformofinitializationisshortforthestandardarray

initializationform:



constcharm1[40]={'L',

'i','m','i','t','','y','o','u','r','s','e','l',

'f','','t','o','','o','n','e','',

'l','i','n','e','\",'s','','w','o','r',

't','h','.','\0'

};



Notetheclosingnullcharacter.Withoutit,youhaveacharacter

array,butnotastring.

Whenyouspecifythearraysize,besurethatthenumberof

elementsisatleastonemore(thatnullcharacteragain)than

thestringlength.Anyunusedelementsareautomatically

initializedto0(whichincharformisthenullcharacter,notthe

zerodigitcharacter).SeeFigure11.1.



Figure11.1.Initializinganarray.



Often,itisconvenienttoletthecompilerdeterminethearray

size;recallthatifyouomitthesizeinaninitializingdeclaration,

thecompilerdeterminesthesizeforyou:



constcharm2[]="Ifyoucan'tthinkofanything,fakeit.";



Initializingcharacterarraysisonecasewhenitreallydoes

makesensetoletthecompilerdeterminethearraysize.That's

becausestring-processingfunctionstypicallydon'tneedto

knowthesizeofthearraybecausetheycansimplylookforthe

nullcharactertomarktheend.

Notethattheprogramhadtoassignasizeexplicitlyforthe

arrayname:



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

Chapter 11. Character Strings and String Functions

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

×