University of Washington Computer Programming IOverviewSlide 4Slide 5String Representation (1)String Representation (2)String Representation (3)String OperationsWhat You Can’t DoString Library: <string.h>String Length: strlenSlide 13String Assignment: strcpySlide 15Slide 16Slide 17Slide 18String Concatenation: strcatSlide 20Slide 21String Comparison: strcmpSlide 23Using strcmp (1)Using strcmp (2)String I/OSlide 28Slide 29Slide 30Slide 31Slide 32N-1University of WashingtonComputer Programming ILecture 19: Strings© 2000 UW CSEN-2OverviewConcepts this lectureString constants Null-terminated array representationString library <strlib.h>String initializersArrays of stringsN-4Character Data in ProgramsNames, messages, labels, headings, etc.All of these are common in computer applicationsAll involve characters: usually multiple charactersSo far, our ability to handle these things in C is very limitedN-5Characters and StringsCharacter constants (literals): single quotes ‘a’, ‘A’, ‘0’, ‘1’, ‘\n’, ‘ ’, ‘B’, ‘i’, ‘l’ , ‘\0’null characterString constants (literals): double quotes"Bill is very rich"“The answer is %.2f. \n"N-6String Representation (1)Strings are stored in char arraysProgramming convention: a null character ‘\0’ is stored at the end string representation"sample"s a m p l e\0N-7String Representation (2)‘\0’ included in string constants automaticallyProgrammer must take pains to be sure it is present elsewhere when neededs a m p l e\0N-8String Representation (3)Character arrays holding strings must have room for ‘\0’ following the actual dataThe empty string "" occupies 1 charCharacter and string constants are not the same: ‘x’ and "x" are different. How?s a m p l e\0N-9String OperationsCommon needed operations:Copy (assignment)CompareFind lengthConcatenate (combine strings)I/OUnfortunately...s a m p l e\0N-10What You Can’t DoStrings are arraysThey have the limitations of arraysCan’t assign one string to another with =Can’t compare strings with ==, <=But there are library functions to help do such thingss a m p l e\0N-11String Library: <string.h>Standard C includes a library of string functionsuse #include <string.h>Library functions: Require proper null-terminated (‘\0’) strings as arguments Produce null-terminated strings as results (usually) s a m p l e\0N-12String Length: strlenstrlen returns the length of its string argumentDoes not count the null ‘\0’ at the endExamples:The length of "A" is 1The length of "" is 0k = strlen("null-terminated string");stores 22 in kN-13/* * return the length of string s, i.e., * number of characters before terminating '\0', * or equivalently, index of first '\0'.*/int strlen( char s[ ] ) {int n = 0; while ( s[n] != '\0')n = n + 1 ;return n;}A strlen implementationN-14String Assignment: strcpystrcpy(dest, source);Copies characters from source to destCopies up to, and including the first ‘\0’ foundBe sure that dest is large enough to hold the result!N-15String Assignment:Examples#include <string.h>...char medium[21] ;char big[1000] ;char small[5] ;strcpy(medium, "Four score and seven" ) ;medium: Four score and seven\0N-16String Assignment:Exampleschar medium[21 ];char big[1000] ;char small[5] ;strcpy(big, medium) ;strcpy(big, "Bob") ;big: Four score and seven\0?????...big: Bob\0 score and seven\0?????...N-17String Assignment Dangerschar medium[ 21];char big[1000] ;char small[5] ;strcpy(small, big) ;strcpy(small, medium) ; /* looks like trouble... */small: Bob\0?small: Four score and seven\0N-18A strcpy implementation/* copy source string into dest, stopping with '\0' */void strcpy(char dest[ ], char source[ ]){int i = 0;while (source[ i ] != ‘\0’) {dest[ i ] = source[ i ] ; i ++;}dest[ i ] = ‘\0’ ;}N-19String Concatenation: strcatTo append means to place one string directly after another"chop" appended to "lamb" should result in "lambchop"strcat(dest, source);Appends characters from source to dest Copy is stored starting at first ‘\0’ in destCopies up to, and including the first ‘\0’ in sourceBe sure that dest is large enough!N-20Using strcat (1)#include <string.h>...char str1[5] , str2[5] , str3[11];strcpy(str1, "lamb");strcpy(str2, "chop");str1 ? ? ? ? ?str3 ? ? ? ? ? ? ? ? ? ? ?str2 ? ? ? ? ? c h o p \0 l a m b \0N-21Using strcat (2)strcpy(str3, str1);strcat(str3, str2);str1 l a m b \0str3 ? ? ? ? ? ? ? ? ? ? ?str2 c h o p \0 l a m b \0 c h o p \0N-22String Comparison: strcmpstrcmp(s1, s2);Compares s1 to s2 and returns an int describing the comparisonNegative if s1 is less than s2Zero if s1 equals s2Positive if s1 is greater than s2N-23Comparing Stringsstrcmp compares corresponding characters until it finds a mismatch."lamb" is less than "wolf""lamb" is less than "lamp""lamb" is less than "lambchop"N-24Using strcmp (1)Don't treat the result of strcmp as a Boolean!Test the result as an integerif (strcmp(s1,s2) == 0)printf("same\n");N-25Using strcmp (2)If you treat the result of strcmp as a Boolean, it probably won’t do what you wantif (strcmp(s1,s2)) printf("yikes!");prints yikes if s1 and s2 are different!N-26String I/Oscanf and printf can read and write C stringsFormat code is %s‘\0’ termination handled properlyBe sure there’s enough space for data plus ‘\0’ on input!#define MAX_INPUT 2000char buffer [MAX_INPUT];…scanf("%s", buffer);N-28Many Functions in <string.h>strcat, strncat concatenationstrcmp, strncmp comparisonstrtod, strtol, strtoul conversionLots of others: check your favorite reference.Related useful functions in <ctype.h>operations on a single char:convert case, check category, etc.N-29Using Libraries of FunctionsTo use strings effectively in C, use functions from string.hUsing libraries is very typical of C programmingANSI C standard libraries such as stdio.h, string.h, ctype.hApplication-specific libraries: (thousands of them exist)You can’t be an effective programmer without being able to quickly master new libraries of functionsN-30Bonus: String Initializerschar pet[5] = { ‘l’, ‘a’, ‘m’, ‘b’, ‘\0’ } ;char pet[5] ;pet[0] = ‘l’ ; pet[1] = ‘a’ ; pet[2] = ‘m’ ; pet[3] = ‘b’ ; pet[4] = ‘\0’ ;char pet[5] = "lamb" ;But not:char pet[5];pet = “lamb” ; /* No array assignment in C */Remember that initializers are not assignment statements!all equivalentN-31Bonus: Arrays of Stringschar month[12][10] = {"January","February",..."September", /*
View Full Document