NT-1CSE 142Computer Programming IStrings© 2000 UW CSET-2OverviewConcepts this lectureString constants Null-terminated array representationString library <string.h>String initializersArrays of stringsT-3Chapter 9Read Sections 9.1, 9.2, and 9.4:9.1: String BasicsTable 9.1 for summary of common functions9.2: String Assignment9.3: String Concatenation9.4: String ComparisonT-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 limitedT-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"T-6String RepresentationStrings are stored in char arraysProgramming convention: a null character ’\0’ is stored at the endstringrepresentation"sample"s a m p l e\0NT-7’\0’ in Strings’\0’ is not included in strings automatically’\0’ is included in string constants automatically Programmer must take pains to be sure ’\0’ is present elsewhere when neededs a m p l e\0T-8Leaving Room for ’\0’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\0T-9String OperationsCommon needed operations:Copy (assignment)CompareFind lengthConcatenate (combine strings)I/OUnfortunately...s a m p l e\0T-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\0T-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\0T-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 kNT-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 implementationT-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!T-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\0T-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?????...T-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\0T-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’ ;}NT-19Appending and ConcatenationTo append means to place one string directly after another"chop" appended to "lamb" should result in "lambchop"Also referred to as concatenationT-20String Concatenation: strcat<string.h> function:strcat(dest, source);Appends characters from source to destCopy is stored starting at first ’\0’ in destCopies up to, and including the first ’\0’ in sourceBe sure that dest is large enough!T-21Using 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 \0l a m b \0T-22Using strcat (2)strcpy(str3, str1);strcat(str3, str2);str1 l a m b \0str3 ? ? ? ? ? ? ? ? ? ? ?str2 c h o p \0l a m b \0c h o p \0T-23String 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 s2T-24Comparing Stringsstrcmp compares corresponding characters until it finds a mismatch."lamb" is less than "wolf""lamb" is less than "lamp""lamb" is less than "lambchop"NT-25Using 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");T-26Using 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!T-27String I/Oscanf and printf can read and write C stringsFormat code is %sprintf assumes '\0' is presentscanf will automatically insert ’\0’ at the endBe sure the array has room for it!T-28Spot the Security Hole#define MAX_INPUT 200char buffer [MAX_INPUT];…scanf("%s", buffer);T-29Many 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 (to upper or lower)check category (is char a number, etc.)many othersT-30Using 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.h, math.hApplication-specific libraries: (thousands of them exist)You can’t be an effective programmer without being able to quickly master new libraries of functionsNT-31Bonus: 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 equivalentT-32Bonus: Arrays of Stringschar month[12][10] = {"January","February",..."September", /* longest month: 9 letters */..."December" } ;...printf ("%s is hot \n", month[7] ); /*
View Full Document