C程序設計基礎 英文版 課件 Chapter 8 Strings_第1頁
C程序設計基礎 英文版 課件 Chapter 8 Strings_第2頁
C程序設計基礎 英文版 課件 Chapter 8 Strings_第3頁
C程序設計基礎 英文版 課件 Chapter 8 Strings_第4頁
C程序設計基礎 英文版 課件 Chapter 8 Strings_第5頁
已閱讀5頁,還剩53頁未讀 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

Chapter8StringsFangWangOutlines8.1StringConstantsandVariables字符串常量和字符串變量(字符數組)8.2ReadingandWritingStrings字符串讀寫操作8.3AccessingtheCharactersinaString8.4UsingtheCStringLibrary字符串庫函數8.5ArraysofStrings字符串數組2IntroductionThischaptercoversbothstringconstants

(orliterals,asthey’recalledintheCstandard)字符串常量andstringvariables.字符串變量Stringsarearraysofcharactersinwhichaspecialcharacter—thenullcharacter—markstheend.字符串就是以空字符結束的字符數組38.1StringLiterals字符串常量Astring

constantsisasequenceofcharactersenclosedwithindoublequotes:“Helloworld."字符串常量就是雙引號括起來的多個字符。Stringconstantsmaycontainescapesequences.Characterescapesoftenappearinprintf

andscanf

formatstrings.字符串常量里面可以有\開頭的轉義字符Forexample,"Candy\nIs

dandy\nBut

liquor\nIs

quicker.\n

--Ogden

Nash\n"48.1StringLiteralsContinuingaStringLiteralEncounteraverylongstringliteralThebackslashcharacter(\)canbeusedtocontinueastringconstantfromonelinetothenext:

printf("When

you

come

to

a

fork

in

the

road,

take

it.

\ --Yogi

Berra");Whentwoormorestringliteralsareadjacent,thecompilerwilljointhemintoasinglestring.Thisruleallowsustosplitastringliteralovertwoormorelines: printf("When

you

come

to

a

fork

in

the

road,

take

it.

" "--YogiBerra");58.1StringLiteralsHowStringLiteralsAreStoredWhenaCcompilerencountersastringconstantsoflengthninaprogram,itsetsasiden+1bytesofmemoryforthestring.Thismemorywillcontainthecharactersinthestring,plusoneextracharacter—thenull

character—tomarktheendofthestring.Thenullcharacterisrepresentedbythe

’\0’

escapesequence.字符串在存儲的時候,末尾會自動加‘\0’68.1StringLiteralsHowStringLiteralsAreStoredThestring"abc"

isstoredasanarrayoffourcharacters:Thestring""isstoredasasinglenullcharacter:78.1StringLiteralsOperationsonStringLiteralsWecanuseastringconstantwhereverCallowsachar

*

pointer: char*p; p="abc";Thisassignmentmakesppointtothefirstcharacterofthestring.88.2StringVariablesInitializingaStringVariableAstringvariablecanbeinitializedatthesametimeit’sdeclared:

chardate1[8]="June14";Thecompilerwillautomaticallyaddanullcharactersothatdate1canbeusedasastring:

98.2StringVariablesInitializingaStringVariableIftheinitializeristooshorttofillthestringvariable,thecompileraddsextranullcharacters:

chardate2[9]="June14";

Appearanceofdate2:108.2StringVariablesInitializingaStringVariableAninitializerforastringvariablecan’tbelongerthanthevariable,butitcanbethesamelength:

chardate3[7]="June14";There’snoroomforthenullcharacter,sothecompilermakesnoattempttostoreone:

118.2StringVariablesInitializingaStringVariableThedeclarationofastringvariablemayomititslength,inwhichcasethecompilercomputesit:

chardate4[]="June14";Thecompilersetsasideeightcharactersfordate4,enoughtostorethecharactersin"June14"

plusanullcharacter.128.2StringVariablesCharacterArraysversusCharacterPointersThedeclaration

chardate[]="June14";

declaresdatetobeanarray,

Thesimilar-looking

char*date="June14";

declaresdatetobeapointer.138.3ReadingandWritingStringsWritingastringiseasyusingeitherprintforfputs.Toreadastringinasinglestep,wecanuseeitherscanforfgets.148.3ReadingandWritingStringsWritingStringsUsingprintfandputsThe%s

conversionspecificationallowsprintftowriteastring: charstr[]="Arewehavingfunyet?"; printf("%s\n",str); Theoutputwillbe Arewehavingfunyet?printfwritesthecharactersinastringonebyoneuntilitencountersanullcharacter\0.158.3ReadingandWritingStringsWritingStringsUsingprintfandputsToprintpartofastring,usetheconversionspecification%.ps.pisthenumberofcharacterstobedisplayed.Thestatement

printf("%.6s\n",str);

willprint

Arewe

168.3ReadingandWritingStringsWritingStringsUsingprintfandputsThe%ms

conversionwilldisplayastringinafieldofsizem.Ifthestringhasfewerthanmcharacters,itwillberight-justifiedwithinthefield.Toforceleftjustificationinstead,wecanputaminussigninfrontofm.Themandpvaluescanbeusedincombination.Aconversionspecificationoftheform%m.ps

causesthefirst

p

charactersofastringtobedisplayedinafieldofsizem.printf("%6.3s\n",str);

Are178.3ReadingandWritingStringsWritingStringsUsingprintfandputsprintfisn’ttheonlyfunctionthatcanwritestrings.TheClibraryalsoprovidesfputs:charstr[100]=“aaaaa”;

fputs(str,stdout);Afterwritingastring,fputsalwayswritesanadditionalnew-linecharacter.188.3ReadingandWritingStringsReadingStringsUsingscanfandgetsThe%s

conversionspecificationallowsscanftoreadastringintoacharacterarray:charstr[100];

scanf("%s",str);stristreatedasapointer,sothere’snoneedtoputthe&operatorinfrontofstr.Whenscanfiscalled,itskipswhitespace,thenreadscharactersandstorestheminstruntilitencountersawhite-spacecharacter.scanfalwaysstoresanullcharacterattheendofthestring.aaabbb198.3ReadingandWritingStringsReadingStringsUsingscanfandfgetsscanfwon’tusuallyreadafulllineofinput.Anew-linecharacterwillcausescanftostopreading,butsowillaspaceortabcharacter.Toreadanentirelineofinput,wecanusefgets.Propertiesoffgets:Doesn’tskipwhitespacebeforestartingtoreadinput.Readsuntilitfindsanew-linecharacter.Discardsthenew-linecharacterinsteadofstoringit;thenullcharactertakesitsplace.208.3ReadingandWritingStringsReadingStringsUsingscanfandfgetsfgets(str,n,stdin);//readn-1characters+\0Considerthefollowingprogramfragment:charsentence[10];fgets(sentence,sizeof(sentence)-1,stdin);charstr[10];fgets(str,7,stdin);Input:ILOVECHINA!21Classassignment40:input/outputthestringDeclareanarray/stringvariableInput:%sfgetsOutput:%sfputs22#include<stdio.h>#include<stdlib.h>intmain(){charstr[100];fgets(str,99,stdin);fputs(str,stdout);return0;}charstr[100];fgets(str,99,stdin);scanf("%[^\n]%*c",str);ucanusescanf("%[^\n]%*c",str);insteadoffgets(str,n,stdin);^means"NOT".so%*[^\n]scanseverythinguntila\n,butdoesn'tscaninthe\n.%*cscansasinglecharacter,whichwillbethe\nleftoverby%*[^\n]inthiscase.The*instructsscanftodiscardthe\ncharacter.[]meansscanset.238.3ReadingandWritingStringsReadingStringsUsingscanfandgetsAstheyreadcharactersintoanarray,scanfandfgetshavenowaytodetectwhenit’sfull.Consequently,theymaystorecharacterspasttheendofthearray,causingundefinedbehavior.scanfcanbemadesaferbyusingtheconversionspecification%ns

insteadof%s.nisanintegerindicatingthemaximumnumberofcharacterstobestored.getsisinherentlyunsafe;fgetsisamuchbetteralternative.248.3ReadingandWritingStringsReadingStringsCharacterbyCharacter

Standardfunctionssuchasscanfandfgetsautomaticallyputanullcharacterattheendofaninputstring.Ifwe’rewritingourowninputfunction,wemusttakeonthatresponsibility.258.4AccessingtheCharactersinaStringSincestringsarestoredasarrays,wecanusesubscriptingtoaccessthecharactersinastring.Toprocesseverycharacterinastrings,wecansetupaloopthatincrementsacounteriandselectscharactersviatheexpressions[i].268.4AccessingtheCharactersinaStringAfunctionthatcountsthenumberofspacesinastring: intcount_spaces(constchars[]) { intcount=0,i; for(i=0;s[i]!='\0';i++) if(s[i]=='') count++; returncount; }278.5UsingtheCStringLibraryDirectattemptstocopyorcomparestringswillfail.Copyingastringintoacharacterarrayusingthe=operatorisnotpossible: charstr1[10],str2[10];

… str1="abc";/***WRONG***/ str2=str1;/***WRONG***/ Usinganarraynameastheleftoperandof=isillegal.Initializingacharacterarrayusing=islegal,though: charstr1[10]="abc"; Inthiscontext,=isnottheassignmentoperator.288.5UsingtheCStringLibraryAttemptingtocomparestringsusingarelationalorequalityoperatorislegalbutwon’tproducethedesiredresult: if(str1==str2)…/***WRONG***/Thisstatementcomparesstr1andstr2aspointers.Sincestr1andstr2havedifferentaddresses,theexpressionstr1

==

str2

musthavethevalue0.298.5UsingtheCStringLibraryTheClibraryprovidesarichsetoffunctionsforperformingoperationsonstrings.Programsthatneedstringoperationsshouldcontainthefollowingline:

#include<string.h>Insubsequentexamples,assumethatstr1andstr2arecharacterarraysusedasstrings.308.5UsingtheCStringLibraryThestrcpy(StringCopy)FunctionPrototypeforthestrcpyfunction:char*strcpy(char*s1,constchar*s2);strcpycopiesthestrings2intothestrings1.Tobeprecise,weshouldsay“strcpycopiesthestringpointedtobys2intothearraypointedtobys1.”strcpyreturnss1(apointertothedestinationstring).318.5UsingtheCStringLibraryThestrcpy(StringCopy)FunctionAcallofstrcpythatstoresthestring"abcd"

instr2:charstr2[20]; strcpy(str2,"abcd");

/*str2nowcontains"abcd"*/Acallthatcopiesthecontentsofstr2intostr1:charstr1[20];

strcpy(str1,str2); /*str1nowcontains"abcd"*/328.5UsingtheCStringLibraryThestrcpy(StringCopy)FunctionInthecallstrcpy(str1,

str2),

strcpyhasnowaytocheckthatthestr2stringwillfitinthearraypointedtobystr1.Ifitdoesn’t,undefinedbehavioroccurs.338.5UsingtheCStringLibraryThestrcpy(StringCopy)FunctionCallingthestrncpyfunctionisasafer,albeitslower,waytocopyastring.strncpyhasathirdargumentthatlimitsthenumberofcharactersthatwillbecopied.Acallofstrncpythatcopiesstr2intostr1:

strncpy(str1,str2,sizeof(str1));348.5UsingtheCStringLibraryThestrcpy(StringCopy)Functionstrncpywillleavestr1withoutaterminatingnullcharacterifthelengthofstr2

isgreaterthanorequaltothesizeofthestr1array.Asaferwaytousestrncpy:

strncpy(str1,str2,sizeof(str1)-1); str1[sizeof(str1)-1]='\0';Thesecondstatementguaranteesthatstr1isalwaysnull-terminated.358.5UsingtheCStringLibraryThestrlen(StringLength)FunctionPrototypeforthestrlenfunction:

size_tstrlen(constchar*s);size_tisatypedefnamethatrepresentsoneofC’sunsignedintegertypes.368.5UsingtheCStringLibraryThestrlen(StringLength)Functionstrlenreturnsthelengthofastrings,notincludingthenullcharacter.Examples: intlen; len

=

strlen("abc");

/*

len

is

now

3

*/ len

=

strlen("");

/*

len

is

now

0

*/ strcpy(str1,

"abc"); len

=

strlen(str1);

/*

len

is

now

3

*/378.5UsingtheCStringLibraryThestrcat(StringConcatenation)FunctionPrototypeforthestrcatfunction:

char*strcat(char*s1,constchar*s2);strcat

appendsthecontentsofthestrings2totheendofthestrings1.Itreturnss1(apointertotheresultingstring).strcatexamples:charstr1[20],str2[20]; strcpy(str1,"abc"); strcat(str1,"def");

/*str1nowcontains"abcdef"*/ strcpy(str1,"abc"); strcpy(str2,"def"); strcat(str1,str2); /*str1nowcontains"abcdef"*/

388.5UsingtheCStringLibraryThestrcat(StringConcatenation)FunctionAswithstrcpy,thevaluereturnedbystrcatisnormallydiscarded.Thefollowingexampleshowshowthereturnvaluemightbeused: charstr1[20],str2[20];strcpy(str1,"abc"); strcpy(str2,"def"); strcat(str1,strcat(str2,"ghi")); /*str1nowcontains"abcdefghi"; str2contains"defghi"*/398.5UsingtheCStringLibraryThestrcat(StringConcatenation)Functionstrcat(str1,

str2)

causesundefinedbehaviorifthestr1arrayisn’tlongenoughtoaccommodatethecharactersfromstr2.Example: charstr1[6]="abc"; strcat(str1,"def");/***WRONG***/str1islimitedtosixcharacters,causingstrcattowritepasttheendofthearray.408.5UsingtheCStringLibraryThestrcat(StringConcatenation)FunctionThestrncatfunctionisasaferbutslowerversionofstrcat.Likestrncpy,ithasathirdargumentthatlimitsthenumberofcharactersitwillcopy.Acallofstrncat:

strncat(str1,str2,sizeof(str1)-1);strncatwillterminatestr1

withanullcharacter,whichisn’tincludedinthethirdargument.418.5UsingtheCStringLibraryThestrcmp(StringComparison)FunctionPrototypeforthestrcmpfunction:

intstrcmp(constchar*s1,constchar*s2);strcmpcomparesthestringss1ands2,returningavaluelessthan,equalto,orgreaterthan0,dependingonwhethers1islessthan,equalto,orgreaterthans2.charstr1[20]=“abc”,str2[20]=“abdef”;if(strcmp(str1,str2)==0)…//same428.5UsingtheCStringLibraryThestrcmp(StringComparison)FunctionTestingwhetherstr1

islessthanstr2:if(strcmp(str1,str2)<0)/*isstr1<str2?*/ …Testingwhetherstr1islessthanorequaltostr2:if(strcmp(str1,str2)<=0)/*isstr1<=str2?*/ …Bychoosingtheproperoperator(<,<=,>,>=,==,!=),wecantestanypossiblerelationshipbetweenstr1andstr2.438.5UsingtheCStringLibraryThestrcmp(StringComparison)Functionstrcmpconsiderss1tobelessthan

s2ifeitheroneofthefollowingconditionsissatisfied:Thefirsticharactersofs1ands2match,butthe(i+1)stcharacterofs1islessthanthe(i+1)stcharacterofs2.Allcharactersofs1matchs2,buts1isshorterthans2.448.5UsingtheCStringLibraryThestrcmp(StringComparison)FunctionAsitcomparestwostrings,strcmplooksatthenumericalcodesforthecharactersinthestrings.Someknowledgeoftheunderlyingcharactersetishelpfultopredictwhatstrcmpwilldo.ImportantpropertiesofASCII:A–Z,a–z,and0–9haveconsecutivecodes.Allupper-caselettersarelessthanalllower-caseletters.Digitsarelessthanletters.Spacesarelessthanallprintingcharacters.458.5UsingtheCStringLibrarysprintfissimilartoprintf,exceptthatitwritesoutputintoastring.

inta=3,b=5;charstr1[20]="abcd";sprintf(str1,"%d%d",a,b);fputs(str1,stdout);//35//35\0d468.5UsingtheCStringLibrary

scanf("%2d",&day);sscanf("12345","%4s",str);478.7ArraysofStringsThereismorethanonewaytostoreanarrayofstrings.Oneoptionistouseatwo-dimensionalarrayofcharacters,withonestringperrow: char

planets[][8]

=

{"Mercury",

"Venus",

"Earth",

"Mars",

"Jupiter",

"Saturn",

"Uranus",

"Neptune",

"Pluto"};Thenumberofrowsinthearraycanbeomitted,butwemustspecifythenumberofcolumns.488.7ArraysofStringsUnfortunately,theplanetsarraycontainsafairbitofwastedspace(extranullcharacters):49Romantime[12][5]={"I","II","III","IV","V","VI","VII","VIII","IX

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論