Tải bản đầy đủ - 0 (trang)
Chapter 18. Class string and String Stream Processing

Chapter 18. Class string and String Stream Processing

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

Chapter18.ClassstringandString

StreamProcessing

Thedifferencebetweenthealmost-rightwordand

therightwordisreallyalargematterit'sthe

differencebetweenthelightningbugandthe

lightning.

MarkTwain

Ihavemadethisletterlongerthanusual,becauseI

lackthetimetomakeitshort.

BlaisePascal

Mum'stheword.

MigueldeCervantes

Suittheactiontotheword,thewordtotheaction;

withthisspecialobservance,thatyouo'erstepnot

themodestyofnature.

WilliamShakespeare

OBJECTIVES

Inthischapteryouwilllearn:

TouseclassstringfromtheC++StandardLibrarytotreat

stringsasfull-fledgedobjects.

Toassign,concatenate,compare,searchandswapstrings.



Todeterminestringcharacteristics.

Tofind,replaceandinsertcharactersinastring.

ToconvertstringstoC-stylestringsandviceversa.

Tousestringiterators.

Toperforminputfromandoutputtostringsinmemory.



[Page884]

Outline

18.1Introduction

18.2stringAssignmentandConcatenation

18.3Comparingstrings

18.4Substrings

18.5Swappingstrings

18.6stringCharacteristics

18.7FindingStringsandCharactersinastring

18.8ReplacingCharactersinastring

18.9InsertingCharactersintoastring

18.10ConversiontoC-Stylechar*Strings

18.11Iterators

18.12StringStreamProcessing



18.13Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises



[Page884(continued)]



18.1.Introduction

TheC++classtemplatebasic_stringprovidestypicalstringmanipulationoperationssuchascopying,searching,etc.The

templatedefinitionandallsupportfacilitiesaredefinedin

namespacestd;theseincludethetypedefstatement

typedefbasic_stringstring;



thatcreatesthealiastypestringforbasic_string.A

typedefalsoisprovidedforthewchar_ttype.Typewchar_t[1]

storescharacters(e.g.,two-bytecharacters,four-byte

characters,etc.)forsupportingothercharactersets.Weuse

stringexclusivelythroughoutthischapter.Tousestrings,include

headerfile.

[1]Typewchar_tcommonlyisusedtorepresentUnicode®,whichdoeshave16-bitcharacters,butthesizeof

wchar_tisnotfixedbythestandard.TheUnicodeStandardoutlinesaspecificationtoproduceconsistent

encodingoftheworld'scharactersandsymbols.TolearnmoreabouttheUnicodeStandard,visit

www.unicode.org.



Astringobjectcanbeinitializedwithaconstructorargument

suchas

stringtext("Hello");//createsstringfromconstchar*



whichcreatesastringcontainingthecharactersin"Hello",or

withtwoconstructorargumentsasin

stringname(8,'x');//stringof8'x'characters



whichcreatesastringcontainingeight'x'characters.Class

stringalsoprovidesadefaultconstructor(whichcreatesan

emptystring)andacopyconstructor.Anemptystringisa

stringthatdoesnotcontainanycharacters.

Astringalsocanbeinitializedviathealternateconstruction

syntaxinthedefinitionofastringasin

stringmonth="March";//sameas:stringmonth("March");



[Page885]

Rememberthatoperator=intheprecedingdeclarationisnotan

assignment;ratheritisanimplicitcalltothestringclass

constructor,whichdoestheconversion.

Notethatclassstringprovidesnoconversionsfromintorcharto

stringinastringdefinition.Forexample,thedefinitions

stringerror1='c';

stringerror2('u');

stringerror3=22;

stringerror4(8);



resultinsyntaxerrors.Notethatassigningasinglecharacterto

astringobjectispermittedinanassignmentstatementasin

string1='n';



CommonProgrammingError18.1

Attemptingtoconvertanintorchartoastringviaan

initializationinadeclarationorviaaconstructor

argumentisacompilationerror.



UnlikeC-stylechar*strings,stringsarenotnecessarilynull

terminated.[Note:TheC++standarddocumentprovidesonlya

descriptionoftheinterfaceforclassstringimplementationis

platformdependent.]Thelengthofastringcanberetrieved

withmemberfunctionlengthandwithmemberfunctionsize.

Thesubscriptoperator,[],canbeusedwithstringstoaccess

andmodifyindividualcharacters.LikeC-stylestrings,strings

haveafirstsubscriptof0andalastsubscriptoflength()1.

Moststringmemberfunctionstakeasargumentsastarting

subscriptlocationandthenumberofcharactersonwhichto

operate.

Thestreamextractionoperator(>>)isoverloadedtosupport

strings.Thestatement

stringstringObject;

cin>>stringObject;



readsastringfromthestandardinputdevice.Inputisdelimited

bywhite-spacecharacters.Whenadelimiterisencountered,

theinputoperationisterminated.Functiongetlinealsois

overloadedforstrings.Thestatement

stringstring1;



getline(cin,string1);



readsastringfromthekeyboardintostring1.Inputisdelimited

byanewline('\n'),sogetLinecanreadalineoftextintoastring

object.







[Page885(continued)]



18.2.stringAssignmentandConcatenation

Figure18.1demonstratesstringassignmentandconcatenation.

Line7includesheaderforclassstring.Thestrings

string1,string2andstring3arecreatedinlines1214.Line16

assignsthevalueofstring1tostring2.Aftertheassignment

takesplace,string2isacopyofstring1.Line17usesmember

functionassigntocopystring1intostring3.Aseparatecopyis

made(i.e.,string1andstring3areindependentobjects).Class

stringalsoprovidesanoverloadedversionofmemberfunction

assignthatcopiesaspecifiednumberofcharacters,asin



targetString.assign(sourceString,start,numberOfCharacters);



[Page886]

wheresourceStringisthestringtobecopied,startisthestarting

subscriptandnumberOfCharactersisthenumberofcharactersto

copy.



Figure18.1.Demonstratingstringassignment

andconcatenation.

(Thisitemisdisplayedonpages886-887intheprint

version)



1//Fig.18.1:Fig18_01.cpp

2//Demonstratingstringassignmentandconcatenation.

3#include

4usingstd::cout;

5usingstd::endl;

6

7#include



8usingstd::string;

9

10intmain()

11{

12stringstring1("cat");

13stringstring2;

14stringstring3;

15

16string2=string1;//assignstring1tostring2

17string3.assign(string1);//assignstring1tostring3

18cout<<"string1:"<
19<<"\nstring3:"<
20

21//modifystring2andstring3

22string2[0]=string3[2]='r';

23

24cout<<"Aftermodificationofstring2andstring3:\n"<<"string1:"

25<
26

27//demonstratingmemberfunctionat

28for(inti=0;i
29cout<
30

31//declarestring4andstring5

32stringstring4(string1+"apult");//concatenation

33stringstring5;

34

35//overloaded+=

36string3+="pet";//create"carpet"

37string1.append("acomb");//create"catacomb"

38

39//appendsubscriptlocations4throughendofstring1to

40//createstring"comb"(string5wasinitiallyempty)

41string5.append(string1,4,string1.length()-4);

42

43cout<<"\n\nAfterconcatenation:\nstring1:"<
44<<"\nstring2:"<
45<<"\nstring4:"<
46return0;

47}//endmain



string1:cat

string2:cat

string3:cat

Aftermodificationofstring2andstring3:

string1:cat

string2:rat

string3:car



Afterconcatenation:

string1:catacomb

string2:rat

string3:carpet

string4:catapult

string5:comb



Line22usesthesubscriptoperatortoassign'r'tostring3[2]

(forming"car")andtoassign'r'tostring2[0](forming"rat").

Thestringsarethenoutput.



[Page887]

Lines2829outputthecontentsofstring3onecharacterata

timeusingmemberfunctionat.Memberfunctionatprovides

checkedaccess(orrangechecking);i.e.,goingpasttheend

ofthestringthrowsanout_of_rangeexception.(SeeChapter16

foradetaileddiscussionofexceptionhandling.)Notethatthe

subscriptoperator,[],doesnotprovidecheckedaccess.Thisis

consistentwithitsuseonarrays.



CommonProgrammingError18.2

Accessingastringsubscriptoutsidetheboundsofthe

stringusingfunctionatisalogicerrorthatcausesan

out_of_rangeexception.



CommonProgrammingError18.3



Accessinganelementbeyondthesizeofthestringusing

thesubscriptoperatorisanunreportedlogicerror.



Stringstring4isdeclared(line32)andinitializedtotheresultof

concatenatingstring1and"apult"usingtheoverloadedaddition

operator,+,whichforclassstringdenotesconcatenation.Line

36usestheadditionassignmentoperator,+=,toconcatenate

string3and"pet".Line37usesmemberfunctionappendto

concatenatestring1and"acomb".

Line41appendsthestring"comb"toemptystringstring5.This

memberfunctionispassedthestring(string1)toretrieve

charactersfrom,thestartingsubscriptinthestring(4)andthe

numberofcharacterstoappend(thevaluereturnedby

string1.length()-4).



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

Chapter 18. Class string and String Stream Processing

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

×