中国高校课件下载中心 》 教学资源 》 大学文库

英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 11 - Strings

文档信息
资源类别:文库
文档格式:PDF
文档页数:3
文件大小:74.01KB
团购合买:点击进入团购
内容简介
英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 11 - Strings
刷新页面文档预览

StringsLecture 11.Wehavealreadycomeacrossstrings2e.g.puts("Hello");:Here"Hello"is a literal string or string constant.Wecanalsohavestringvariables:InCstringsarenotasimpledatatype:Astringisanull-terminatedarrayofchar.This means that the end of a string is markedbya"sentinel"character,o(ASCllcode=O)DataSrudh10asestidcloterynuntergmeraDeclaringStringDeclaring String VariablesVariables·SimplestBecausethe10'charactermarksthechar message [6] ;end of a string it is ok to havemore.Initialisingspace than neededchar message[6]-*H','e'","1,1',"o*,lo']char message[80]-"Hello"ds ci.hstrings1.c.ButthisissocommonthatCprovidesThe74bytesbeyondtheshorthandthe"o'containrubbishchar message [6]-"Hello"; orat this point but are notchar message[]-"Hello"printedWhichallocatestherequired6bytesautomaticallyDeclaringStringVariablesDeclaringStringVariablesAs with all arrays, overrun must be avoided.Thescanffunctionallowsusto inputastring,.This is particularly easywithstringspecifyingthemaximumnumberofcharactersmanipulation/1wtCE.Xaeleidcatdio.hoasstrings3.cstrings2.c+a(--10.)-Printttera:")printE("Toentered1t.nmentence)

1 1. Introduction 2. Binary Representation 3. Hardware and Software 4. High Level Languages 5. Standard input and output 6. Operators, expression and statements 7. Making Decisions 8. Looping 9. Arrays 10. Basics of pointers 11. Strings 12. Basics of functions 13. More about functions 14. Files 14. Data Structures 16. Case study: lottery number generator Lecture 11 Lecture 11 Strings • We have already come across strings e.g. puts(“Hello”); • Here “Hello” is a literal string or string constant • We can also have string variables • In C strings are not a simple data type • A string is a null-terminated array of char • This means that the end of a string is marked by a “sentinel” character, ‘\0’ (ASCII code=0) h e l l o \0 ? Declaring String Variables • Simplest char message[6]; • Initialising char message[6]={‘H’,’e’,’l’,’l’,’o’,\o’}; • But this is so common that C provides the shorthand char message[6]=“Hello”; or char message[]=“Hello”; • Which allocates the required 6 bytes automatically Declaring String Variables • Because the ‘\0’ character marks the end of a string it is ok to have more space than needed char message[80]=“Hello”; /* Example: strings as null-terminated arrays of char */ #include main() { char myname1[6] = "David"; /* 5 characters + '\0' */ char myname2[] = "Hamill"; /* size set automatically */ int i; printf("My first name is %s.\n", myname1); printf("My last name is %s.\n\n", myname2); for (i = 0; i main() { char myname1[6] = "David"; /* 5 characters + '\0' */ char myname2[] = "Hamill"; /* size set automatically */ int i; printf("My first name is %s.\n", myname1); printf("My last name is %s.\n\n", myname2); for (i = 0; i main() { char word[11]; /* a string, up to 10 characters (+ '\0') */ char sentence[] = "Very interesting."; /* The simplest approach. What might happen if a long word is entered? Why? */ printf("Enter a word, not more than 10 characters: "); scanf("%s", word); printf("You entered \"%s\". %s\n\n", word, sentence); } /* Example: inputting strings from keyboard with scanf */ #include main() { char word[11]; /* a string, up to 10 characters (+ '\0') */ char sentence[] = "Very interesting."; /* The simplest approach. What might happen if a long word is entered? Why? */ printf("Enter a word, not more than 10 characters: "); scanf("%s", word); printf("You entered \"%s\". %s\n\n", word, sentence); } strings2.c strings2.c /* Example: inputting strings from keyboard with scanf */ #include main() { char word[11]; /* a string, up to 10 characters (+ '\0') */ char sentence[] = "Very interesting."; /* A better approach. What happens if a long word is entered? Why? */ printf("Enter a word, not more than 10 characters: "); scanf("%10s", word); printf("You entered \"%s\". %s\n\n", word, sentence); } /* Example: inputting strings from keyboard with scanf */ #include main() { char word[11]; /* a string, up to 10 characters (+ '\0') */ char sentence[] = "Very interesting."; /* A better approach. What happens if a long word is entered? Why? */ printf("Enter a word, not more than 10 characters: "); scanf("%10s", word); printf("You entered \"%s\". %s\n\n", word, sentence); } Declaring String Variables • The scanf function allows us to input a string, specifying the maximum number of characters strings3.c strings3.c

StringVariablesasPointersto charManipulating StringsBecause strings areactually arrays,in·As with all arrays, westrings5.cgeneral wemustoperateon individualcan access individualelements,e.g.wecantdoelementsusingachar message[40] ;pointer. This ismessage-"Hello":declared asTodo this we wouldprobablyuseaforloopchar* pc;and set each item (message[ij) individuallyNote that this only.Becausethisisapainandaverycommoncreates a pointer, itrequirement C has a standard library of stringdoes notallocateanymanipulationfunctionswhich youmemory to itcan#include#include #include Someofitsuseful routines arestrlen (s) :- gives the length ofstrings6.cstring s (not countfing the 10)stpy(d);copy stings (source tostingd (destinaticn)atrcat (d, s); - concatenate (join) string s onto the end of string dr(s1,a2)atrcmp (s1, s2); compare strings s1 and s2position of s2within st·String comparison isdoneona char-by-charbasis.StartingatpositionOandendingwhenao'isfoundineitherstring.The chars arecompared numerically,usingtheirASCll codes.Theresult isnegativeifs1s2Useful characterfunctionsPrinting to a string:Thestandardlibrarycontainssome.Weuseprintftoprinttothescreenuseful routines to tellus about individualSimilarlywecanusesprintf toprinttoa stringcharacters.Wecanalso scanfroma stringusingsscanfSaloer(c),faupper(c),ladsgit(c),laspace(c),iapunct(c):theyall returntrue/falseifcharcislowercase,utted priaiegtaapuppercase sprintf.cFlahacanalyse2.c2

2 String Variables as Pointers to char • As with all arrays, we can access individual elements using a pointer. This is declared as char* pc; • Note that this only creates a pointer, it does not allocate any memory to it /* Example: string variables as pointers to char */ #include main() { char town[] = "Guildford"; /* array of char */ char *pString; /* pointer to char */ int i; pString = town + 5; puts(town); puts(pString); for (pString = town, i = 8; i >= 0; i-) putchar(pString[i]); /* or putchar(*(pString + i)); */ putchar('\n'); pString = town; *pString = 'B'; pString += 5; *pString = '\0'; puts(town); } /* Example: string variables as pointers to char */ #include main() { char town[] = "Guildford"; /* array of char */ char *pString; /* pointer to char */ int i; pString = town + 5; puts(town); puts(pString); for (pString = town, i = 8; i >= 0; i-) putchar(pString[i]); /* or putchar(*(pString + i)); */ putchar('\n'); pString = town; *pString = 'B'; pString += 5; *pString = '\0'; puts(town); } Guildford ford drofdliuG Build Guildford ford drofdliuG Build strings5.c strings5.c Manipulating Strings • Because strings are actually arrays, in general we must operate on individual elements, e.g. we cant do char message[40]; message=“Hello”; • To do this we would probably use a for loop and set each item (message[i]) individually • Because this is a pain and a very common requirement C has a standard library of string manipulation functions which you can #include #include • Some of its useful routines are strcpy(d,s); - copy string s (source) to string d (destination) strcat(d,s); - concatenate (join) string s onto the end of string d strcmp(s1,s2); - compare strings s1 and s2 • String comparison is done on a char-by-char basis • Starting at position 0 and ending when a ‘\0’ is found in either string • The chars are compared numerically, using their ASCII codes • The result is negative if s1s2 #include strlen(s); - gives the length of string s ( not counting the ‘\0’) strstr(s1,s2); - gives the position of s2 within s1 strings6.c strings6.c The nearest town to Guildford is Woking. Woking and Guildford are both in Surrey. Guildford is not the same as Surrey. "How long is a piece of string?" contains 30 characters. "of" occurs at position 20 in "How long is a piece of string?" The nearest town to Guildford is Woking. Woking and Guildford are both in Surrey. Guildford is not the same as Surrey. "How long is a piece of string?" contains 30 characters. "of" occurs at position 20 in "How long is a piece of string?" /* Example: string manipulation using library */ /* At the Unix prompt, enter 'man string' for details */ #include #include main() { char town[] = "Guildford"; char county[] = "Surrey"; char s[80]; char *pc; int n; strcpy(s, "Woking"); /* string copy */ printf("The nearest town to %s is %s.\n\n", town, s); strcat(s, " and "); /* string concatenation */ strcat(s, town); strcat(s, " are both in "); strcat(s, county); strcat(s, ".\n"); puts(s); if (strcmp(town, county) == 0) /* string comparison */ printf("%s is the same as %s.\n", town, county); else printf("%s is not the same as %s.\n", town, county); strcpy(s, "How long is a piece of string?"); n = strlen(s); /* string length, excluding the '\0' */ printf("\n\"%s\" contains %i characters.\n\n", s, n); pc = strstr(s, "of"); /* find a string within a string */ n = pc - s; /* subtract the pointers */ printf("\"of\" occurs at position %i in \"%s\"\n", n, s); } /* Example: string manipulation using library */ /* At the Unix prompt, enter 'man string' for details */ #include #include main() { char town[] = "Guildford"; char county[] = "Surrey"; char s[80]; char *pc; int n; strcpy(s, "Woking"); /* string copy */ printf("The nearest town to %s is %s.\n\n", town, s); strcat(s, " and "); /* string concatenation */ strcat(s, town); strcat(s, " are both in "); strcat(s, county); strcat(s, ".\n"); puts(s); if (strcmp(town, county) == 0) /* string comparison */ printf("%s is the same as %s.\n", town, county); else printf("%s is not the same as %s.\n", town, county); strcpy(s, "How long is a piece of string?"); n = strlen(s); /* string length, excluding the '\0' */ printf("\n\"%s\" contains %i characters.\n\n", s, n); pc = strstr(s, "of"); /* find a string within a string */ n = pc - s; /* subtract the pointers */ printf("\"of\" occurs at position %i in \"%s\"\n", n, s); } strings6.c strings6.c Printing to a string • We use printf to print to the screen • Similarly we can use sprintf to print to a string • We can also scan from a string using sscanf /* Example: formatted printing to a string using sprintf */ /* Like printf, but prints to a string instead of standard output */ #include main() { char format[40], output[40]; float x; puts("Enter a positive or negative floating point number:"); scanf("%f", &x); /* Assemble format string at run time: */ sprintf(format, "You entered %s\n", (x >= 0) ? "%6.3f" : "%5.3E"); /* Generate output string: */ sprintf(output, format, x); puts(output); } /* Example: formatted printing to a string using sprintf */ /* Like printf, but prints to a string instead of standard output */ #include main() { char format[40], output[40]; float x; puts("Enter a positive or negative floating point number:"); scanf("%f", &x); /* Assemble format string at run time: */ sprintf(format, "You entered %s\n", (x >= 0) ? "%6.3f" : "%5.3E"); /* Generate output string: */ sprintf(output, format, x); puts(output); } Enter a positive or negative floating point number: 1.2 You entered 1.200 Enter a positive or negative floating point number: 1.2 You entered 1.200 sprintf.c sprintf.c Useful character functions • The standard library contains some useful routines to tell us about individual characters islower(c), isupper(c), isdigit(c), isspace(c), ispunct(c) • they all return true/false if char c is lower case, upper case. /* Example: analysis of text using library */ /* (Based on analyse.c) */ #include #include main() { char c; int i = 0, lc = 0, uc = 0, dig = 0, ws = 0, pun = 0, oth = 0; puts("Type some text (then ENTER):"); /* Analyse text as it is input: */ while ((c = getchar()) != '\n') { if (islower(c)) /* Example: analysis of text using library */ /* (Based on analyse.c) */ #include #include main() { char c; int i = 0, lc = 0, uc = 0, dig = 0, ws = 0, pun = 0, oth = 0; puts("Type some text (then ENTER):"); /* Analyse text as it is input: */ while ((c = getchar()) != '\n') { if (islower(c)) lc++; else if (isupper(c)) uc++; else if (isdigit(c)) dig++; else if (isspace(c)) ws++; else if (ispunct(c)) pun++; else oth++; } puts("\nYou typed:"); printf("\n%i lower case letters\n", lc); printf("%i upper case letters\n", uc); printf("%i digits\n", dig); printf("%i whitespace\n", ws); printf("%i punctuation\n", pun); printf("%i others\n", oth); } lc++; else if (isupper(c)) uc++; else if (isdigit(c)) dig++; else if (isspace(c)) ws++; else if (ispunct(c)) pun++; else oth++; } puts("\nYou typed:"); printf("\n%i lower case letters\n", lc); printf("%i upper case letters\n", uc); printf("%i digits\n", dig); printf("%i whitespace\n", ws); printf("%i punctuation\n", pun); printf("%i others\n", oth); } analyse2.c analyse2.c

CommonBugsatring errors -swin()strings.bug]er togt.Char sinelo/* s00 */公10 characters:"9Pen3

3 Common Bugs /* BUG ZONE!!! Example: some common string errors */ #include #include /* BUG */ main() { char thing[]; char *wing; char string[41]; char name[5] = "David"; /* BUG */ thing = "What is this thing called love?"; /* BUG */ string = "How long is a piece of string?"; /* BUG */ puts("Enter a word, not more than 10 characters: "); scanf("%s", &string); /* BUG */ puts("Enter a sentence, not more than 40 characters: "); scanf("%s", string); /* BUG */ strcpy(name, "Frankenstein"); /* BUG */ strcpy(wing, "Oh, for the wings of a dove!"); /* BUG */ strcpy("Elvis Presley", string); /* BUG */ strcat(name, "Sir Isaac Newton"); /* BUG */ } /* BUG ZONE!!! Example: some common string errors */ #include #include /* BUG */ main() { char thing[]; char *wing; char string[41]; char name[5] = "David"; /* BUG */ thing = "What is this thing called love?"; /* BUG */ string = "How long is a piece of string?"; /* BUG */ puts("Enter a word, not more than 10 characters: "); scanf("%s", &string); /* BUG */ puts("Enter a sentence, not more than 40 characters: "); scanf("%s", string); /* BUG */ strcpy(name, "Frankenstein"); /* BUG */ strcpy(wing, "Oh, for the wings of a dove!"); /* BUG */ strcpy("Elvis Presley", string); /* BUG */ strcat(name, "Sir Isaac Newton"); /* BUG */ } strings.bug strings.bug

已到末页,全文结束
刷新页面下载完整文档
VIP每日下载上限内不扣除下载券和下载次数;
按次数下载不扣除下载券;
注册用户24小时内重复下载只扣除一次;
顺序:VIP每日次数-->可用次数-->下载券;
相关文档