Page 1
1
Thisdocumentiscopyright(C)StanfordComputerScience,LisaYan,andNickTroccoli,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyMartyStepp,CynthiaLee,ChrisGregg,LisaYan,JerryCainandothers.
CS107,Lecture4CStrings
Reading:K&R(1.9,5.5,AppendixB3)orEssentialCsection3
Page 2
2
CS107 Topic 2: How can a computer represent and
manipulate more complex data like text?
Page 3
3
Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16
• Comparing 19• Copying 21• Concatenating 79• Substrings 90
• Practice:Diamond 99• LiveSession 105
Page 4
4
Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16
• Comparing 19• Copying 21• Concatenating 79• Substrings 90
• Practice:Diamond 99• LiveSession 105
Page 5
5
CharAchar isavariabletypethatrepresentsasinglecharacteror“glyph”.
char letterA = 'A';
char plus = '+';
char zero = '0';
char space = ' ';
char newLine = '\n';
char tab = '\t';
char singleQuote = '\'';
char backSlash = '\\';
Page 6
6
ASCIIUnderthehood,Crepresentseachchar asaninteger (its“ASCIIvalue”).
• Uppercaselettersaresequentiallynumbered• Lowercaselettersaresequentiallynumbered• Digitsaresequentiallynumbered• Lowercaselettersare32morethantheiruppercaseequivalents(bitflip!)
char uppercaseA = 'A'; // Actually 65char lowercaseA = 'a'; // Actually 97char zeroDigit = '0’; // Actually 48
Page 7
7
ASCIIWecantakeadvantageofCrepresentingeachchar asaninteger:
bool areEqual = 'A' == 'A'; // truebool earlierLetter = 'f' < 'c'; // falsechar uppercaseB = 'A' + 1;
int diff = 'c' - 'a'; // 2int numLettersInAlphabet = 'z' – 'a' + 1;
// orint numLettersInAlphabet = 'Z' – 'A' + 1;
Page 8
8
ASCIIWecantakeadvantageofCrepresentingeachchar asaninteger:
// prints out every lowercase characterfor (char ch = 'a'; ch <= 'z'; ch++) {
printf("%c", ch);
}
Page 9
9
Common ctype.h Functions
Function Descriptionisalpha(ch) trueifch is'a' through'z' or 'A' through'Z'
islower(ch) trueifch is'a' through'z'
isupper(ch) trueifch is'A' through'Z'
isspace(ch) trueifch isaspace,tab,newline,etc.
isdigit(ch) trueifch is'0' through'9'
toupper(ch) returnsuppercaseequivalentofaletter
tolower(ch) returnslowercaseequivalentofaletter
Remember:thesereturn achar;theycannotmodifyanexistingchar!Moredocumentationwithman isalpha,man tolower
Page 10
10
Common ctype.h Functionsbool isLetter = isalpha('A'); // truebool capital = isupper('f'); // falsechar uppercaseB = toupper('b');
bool isADigit = isdigit('4'); // true
Page 11
11
Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16
• Comparing 19• Copying 21• Concatenating 79• Substrings 90
• Practice:Diamond 99• LiveSession 105
Page 12
12
C StringsChasnodedicatedvariabletypeforstrings.Instead,astringisrepresentedasanarrayofcharacters withaspecialendingsentinelvalue.
'\0' isthenull-terminatingcharacter;youalwaysneedtoallocateoneextraspaceinanarrayforit.
"Hello"index 0 1 2 3 4 5
char 'H' 'e' 'l' 'l' 'o' '\0'
Page 13
13
String LengthStringsarenot objects.Theydonotembedadditionalinformation(e.g.,stringlength).Wemustcalculatethis!
Wecanusetheprovidedstrlen functiontocalculatestringlength.Thenull-terminatingcharacterdoesnot counttowardsthelength.
int length = strlen(myStr); // e.g. 13
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13
value 'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Caution: strlen is O(N) because it must scan the entire string! We should save the value if we plan to refer to the length later.
Page 14
14
C Strings As ParametersWhenwepassastringasaparameter,itispassedasachar*.Cpassesthelocationofthefirstcharacterratherthanacopyofthewholearray.int doSomething(char *str) {
...}
char myString[6];...doSomething(myString);
Page 15
15
C Strings As ParametersWhenwepassastringasaparameter,itispassedasachar*.Cpassesthelocationofthefirstcharacterratherthanacopyofthewholearray.int doSomething(char *str) {
...str[0] = 'c'; // modifies original string!printf("%s\n", str); // prints cello
}
char myString[6];... // e.g. this string is “Hello”doSomething(myString);
Wecanstilluseachar*thesamewayasachar[].
Page 16
16
Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16
• Comparing 19• Copying 21• Concatenating 79• Substrings 90
• Practice:Diamond 99• LiveSession 105
Page 17
17
Common string.h FunctionsFunction Description
strlen(str) returnsthe#ofcharsinaCstring(beforenull-terminatingcharacter).
strcmp(str1, str2), strncmp(str1, str2, n)
comparestwostrings;returns0ifidentical,<0ifstr1 comesbeforestr2 inalphabet,>0ifstr1 comesafterstr2 inalphabet.strncmpstopscomparingafteratmostn characters.
strchr(str, ch)strrchr(str, ch)
charactersearch:returnsapointertothefirstoccurrenceofch instr,orNULL ifch wasnotfoundinstr.strrchr findthelastoccurrence.
strstr(haystack, needle) stringsearch:returnsapointertothestartofthefirstoccurrenceofneedle inhaystack,orNULL ifneedle wasnotfoundinhaystack.
strcpy(dst, src),strncpy(dst, src, n)
copiescharactersinsrc todst,includingnull-terminatingcharacter.Assumesenoughspaceindst.Stringsmustnotoverlap.strncpystopsafteratmostn chars,anddoesnot addnull-terminatingchar.
strcat(dst, src),strncat(dst, src, n)
concatenatesrc ontotheendofdst.strncat stopsconcatenatingafteratmostn characters.Always addsanull-terminatingcharacter.
strspn(str, accept),strcspn(str, reject)
strspn returnsthelengthoftheinitialpartofstr whichcontainsonlycharactersinaccept.strcspn returnsthelengthoftheinitialpartofstr whichdoesnot containanycharactersinreject.
Page 18
18
Common string.h FunctionsFunction Description
strlen(str) returnsthe#ofcharsinaCstring(beforenull-terminatingcharacter).
strcmp(str1, str2), strncmp(str1, str2, n)
comparestwostrings;returns0ifidentical,<0ifstr1 comesbeforestr2 inalphabet,>0ifstr1 comesafterstr2 inalphabet.strncmpstopscomparingafteratmostn characters.
strchr(str, ch)strrchr(str, ch)
charactersearch:returnsapointertothefirstoccurrenceofch instr,orNULL ifch wasnotfoundinstr.strrchr findthelastoccurrence.
strstr(haystack, needle) stringsearch:returnsapointertothestartofthefirstoccurrenceofneedle inhaystack,orNULL ifneedle wasnotfoundinhaystack.
strcpy(dst, src),strncpy(dst, src, n)
copiescharactersinsrc todst,includingnull-terminatingcharacter.Assumesenoughspaceindst.Stringsmustnotoverlap.strncpystopsafteratmostn chars,anddoesnot addnull-terminatingchar.
strcat(dst, src),strncat(dst, src, n)
concatenatesrc ontotheendofdst.strncat stopsconcatenatingafteratmostn characters.Always addsanull-terminatingcharacter.
strspn(str, accept),strcspn(str, reject)
strspn returnsthelengthoftheinitialpartofstr whichcontainsonlycharactersinaccept.strcspn returnsthelengthoftheinitialpartofstr whichdoesnot containanycharactersinreject.
Many string functions assume valid string input; i.e., ends in a null terminator.
Page 19
19
Comparing StringsWecannot compareCstringsusingcomparisonoperatorslike==,<or>.Thiscomparesaddresses!
// e.g. str1 = 0x7f42, str2 = 0x654dvoid doSomething(char *str1, char *str2) {
if (str1 > str2) { … // compares 0x7f42 > 0x654d!Instead,usestrcmp.
Page 20
20
The string library: strcmpstrcmp(str1, str2):comparestwostrings.• returns0ifidentical• <0ifstr1 comesbeforestr2 inalphabet• >0ifstr1 comesafterstr2 inalphabet.
int compResult = strcmp(str1, str2);if (compResult == 0) {
// equal} else if (compResult < 0) {
// str1 comes before str2 } else {
// str1 comes after str2}
Page 21
21
Copying StringsWecannot copyCstringsusing=.Thiscopiesaddresses!
// e.g. param1 = 0x7f42, param2 = 0x654dvoid doSomething(char *param1, char *param2) {
param1 = param2; // copies 0x654d. Points to same string!param2[0] = 'H'; // modifies the one original string!
Instead,usestrcpy.
Page 22
22
The string library: strcpystrcpy(dst, src):copiesthecontentsofsrc intothestringdst,includingthenullterminator.
char str1[6];strcpy(str1, "hello");
char str2[6];strcpy(str2, str1);str2[0] = 'c';
printf("%s", str1); // helloprintf("%s", str2); // cello
Page 23
23
Copying Strings - strcpychar str1[6];strcpy(str1, "hello");
char str2[6];strcpy(str2, str1);
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' '\0'str2
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' '\0'
? ? ? ? ? ?
Page 24
24
Copying Strings - strcpyWemustmakesurethereisenoughspaceinthedestinationtoholdtheentirecopy,includingthenull-terminatingcharacter.
char str2[6]; // not enough space!strcpy(str2, "hello, world!"); // overwrites other memory!
Writingpastmemoryboundsiscalleda“bufferoverflow”.Itcanallowforsecurityvulnerabilities!
Page 25
25
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
? ? ? ? ? ?str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
- otherprogrammemory-
Page 26
26
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' ? ? ? ? ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 27
27
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' ? ? ? ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 28
28
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' ? ? ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 29
29
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' ? ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 30
30
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 31
31
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 32
32
- otherprogrammemory-' '
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 33
33
- otherprogrammemory-' ' 'w'
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 34
34
- otherprogrammemory-' ' 'w' 'o'
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 35
35
- otherprogrammemory-' ' 'w' 'o' 'r'
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 36
36
- otherprogrammemory-' ' 'w' 'o' 'r' 'l'
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 37
37
- otherprogrammemory-' ' 'w' 'o' 'r' 'l' 'd'
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 38
38
- otherprogrammemory-' ' 'w' 'o' 'r' 'l' 'd' '!'
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 39
39
- otherprogrammemory-' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 40
40
- otherprogrammemory-' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Copying Strings – Buffer Overflowschar str1[14];strcpy(str1, "hello, world!");char str2[6];strcpy(str2, str1); // not enough space - overwrites other memory!
str1
0 1 2 3 4 5
'h' 'e' 'l' 'l' 'o' ','str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 41
41
Copying Strings - strncpystrncpy(dst, src, n):copiesatmostthefirstnbytesfromsrc intothestringdst.Ifthereisnonull-terminatingcharacterinthesebytes,thendst willnotbenullterminated!
// copying "hello"char str2[5];strncpy(str2, "hello, world!", 5); // doesn’t copy '\0'!
Ifthereisnonull-terminatingcharacter,wemaynotbeabletotellwheretheendofthestringisanymore.E.g.strlenmaycontinuereadingintosomeothermemoryinsearchof'\0'!
Page 42
42
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
0 1 2 3 4
? ? ? ? ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 43
43
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
0 1 2 3 4
'h' ? ? ? ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 44
44
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
0 1 2 3 4
'h' 'e' ? ? ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 45
45
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
0 1 2 3 4
'h' 'e' 'l' ? ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 46
46
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
0 1 2 3 4
'h' 'e' 'l' 'l' ?str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 47
47
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
0 1 2 3 4
'h' 'e' 'l' 'l' 'o'str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 48
48
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
0 1 2 3 4
'h' 'e' 'l' 'l' 'o'str2 - otherprogrammemory-
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 49
49
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 50
50
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 51
51
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 52
52
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 53
53
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 54
54
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 55
55
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 56
56
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 57
57
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 58
58
Copying Strings - strncpychar str2[5];strncpy(str2, "hello, world!", 5);int length = strlen(str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4
'h' 'e' 'l' 'l' 'o' - otherprogrammemory-
Page 59
59
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
? ? ? ? ? ? ? ? ? ? ? ? ? ?
Page 60
60
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' ? ? ? ? ? ? ? ? ? ? ? ? ?
Page 61
61
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' ? ? ? ? ? ? ? ? ? ? ? ?
Page 62
62
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' ? ? ? ? ? ? ? ? ? ? ?
Page 63
63
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' ? ? ? ? ? ? ? ? ? ?
Page 64
64
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 65
65
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 66
66
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 67
67
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 68
68
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 69
69
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 70
70
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 71
71
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 72
72
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 73
73
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 74
74
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
Page 75
75
Copying Strings - strncpychar str1[14];strncpy(str1, "hello there", 5);printf("%s\n", str1);
str1
0 1 2 3 4 5 6 7 8 9 10 11 12 13
'h' 'e' 'l' 'l' 'o' ? ? ? ? ? ? ? ? ?
hello⍰⍰J⍰⍰⍰
Page 76
76
Copying Strings - strncpyIfnecessary,wecanaddanull-terminatingcharacterourselves.
// copying "hello"char str2[6]; // room for string and '\0'strncpy(str2, "hello, world!", 5); // doesn’t copy '\0'!str2[5] = '\0'; // add null-terminating char
Page 77
77
String Copying ExerciseWhatvalueshouldgointheblankatright?A. 4B. 5C. 6D. 12E. strlen(“hello”)F. Somethingelse
char str[______];strcpy(str, "hello");
Page 78
78
String ExerciseWhatisprintedoutbythefollowingprogram?
int main(int argc, char *argv[]) {char str[9];strcpy(str, "Hi earth");str[2] = '\0';printf("str = %s, len = %zu\n",
str, strlen(str));return 0;
}
🤔
A. str = Hi, len = 8B. str = Hi, len = 2C. str = Hi earth, len = 8D. str = Hi earth, len = 2E. None/other
12345678
Page 79
79
Concatenating StringsWecannot concatenateCstringsusing+.Thisaddsaddresses!
// e.g. param1 = 0x7f, param2 = 0x65void doSomething(char *param1, char *param2) {
printf("%s", param1 + param2); // adds 0x7f and 0x65!
Instead,usestrcat.
Page 80
80
The string library: str(n)catstrcat(dst, src):concatenatesthecontentsofsrc intothestringdst.strncat(dst, src, n):same,butconcats atmostnbytesfromsrc.
char str1[13]; // enough space for strings + '\0'strcpy(str1, "hello ");strcat(str1, "world!"); // removes old '\0', adds new '\0' at endprintf("%s", str1); // hello world!
Both strcat and strncat remove the old '\0' and add a new one at the end.
Page 81
81
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' '\0' ? ? ? ? ? ?
Page 82
82
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' 'w' ? ? ? ? ? ?
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 83
83
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' ? ? ? ? ?
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 84
84
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' ? ? ? ?
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 85
85
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' ? ? ?
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 86
86
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd' ? ?
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 87
87
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd' '!' ?
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 88
88
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 89
89
Concatenating Stringschar str1[13];strcpy(str1, "hello ");char str2[7];strcpy(str2, "world!");
strcat(str1, str2);
str1
str2
0 1 2 3 4 5 6 7 8 9 10 11 12
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\0'
0 1 2 3 4 5 6
'w' 'o' 'r' 'l' 'd' '!' '\0'
Page 90
90
Substrings and char *Youcanalsocreateachar*variableyourselfthatpointstoanaddresswithininanexistingstring.
char myString[3]; myString[0] = 'H';myString[1] = 'i';myString[2] = '\0';
char *otherStr = myString; // points to 'H'
Page 91
91
Substringschar*sarepointerstocharacters.Wecanusethemtocreatesubstringsoflargerstrings.
// Want just "car"char chars[8];strcpy(chars, "racecar");char *str1 = chars;
0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8
'r' 'a' 'c' 'e' 'c' 'a' 'r' '\0'
str1
0xee
0xf1
chars
Page 92
92
SubstringsSinceCstringsarepointerstocharacters,wecanadjustthepointertoomitcharactersatthebeginning.
// Want just "car"char chars[8];strcpy(chars, "racecar");char *str1 = chars;char *str2 = chars + 4;
0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8
'r' 'a' 'c' 'e' 'c' 'a' 'r' '\0'
str1
0xee
0xf1 str2
0xd2
0xf5
chars
Page 93
93
SubstringsSinceCstringsarepointerstocharacters,wecanadjustthepointertoomitcharactersatthebeginning.
char chars[8];strcpy(chars, "racecar");char *str1 = chars;char *str2 = chars + 4;printf("%s\n", str1); // racecarprintf("%s\n", str2); // car
0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8
'r' 'a' 'c' 'e' 'c' 'a' 'r' '\0'
str1
0xee
0xf1 str2
0xd2
0xf5
chars
Page 94
94
SubstringsSinceCstringsarepointerstocharacters,wecanadjustthepointertoomitcharactersatthebeginning.NOTE: thepointerstillreferstothesamecharacters!
char chars[8];strcpy(chars, "racecar");char *str1 = chars;char *str2 = chars + 4;str2[0] = 'f';printf("%s %s\n", chars, str1);printf("%s\n", str2);
0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8
'r' 'a' 'c' 'e' 'f' 'a' 'r' '\0'
str2
0xd2
0xf5
0xee
0xf1str1
chars
Page 95
95
SubstringsSinceCstringsarepointerstocharacters,wecanadjustthepointertoomitcharactersatthebeginning.NOTE: thepointerstillreferstothesamecharacters!
char chars[8];strcpy(chars, "racecar");char *str1 = chars;char *str2 = chars + 4;str2[0] = 'f';printf("%s %s\n", chars, str1); // racefar racefarprintf("%s\n", str2); // far
0xf1 0xf2 0xf3 0xf4 0xf5 0xf6 0xf7 0xf8
'r' 'a' 'c' 'e' 'f' 'a' 'r' '\0'
str2
0xd2
0xf5
0xee
0xf1str1
chars
Page 96
96
char * vs. char[]char myString[]
vschar *myString
Youcancreatechar*pointerstopointtoanycharacterinanexistingstringandreassignthemsincetheyarejustpointervariables.Youcannot reassignanarray.
char myString[6];strcpy(myString, "Hello");myString = "Another string"; // not allowed!---char *myOtherString = myString;myOtherString = somethingElse; // ok
Page 97
97
SubstringsToomitcharactersattheend,makeanewstringthatisapartialcopyoftheoriginal.
// Want just "race"char str1[8];strcpy(str1, "racecar");
char str2[5];strncpy(str2, str1, 4);str2[4] = '\0';printf("%s\n", str1); // racecarprintf("%s\n", str2); // race
Page 98
98
SubstringsWecancombinepointerarithmeticandcopyingtomakeanysubstringswe’dlike.
// Want just "ace"char str1[8];strcpy(str1, "racecar");
char str2[4];strncpy(str2, str1 + 1, 3);str2[3] = '\0';printf("%s\n", str1); // racecarprintf("%s\n", str2); // ace
Page 99
99
Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16
• Comparing 19• Copying 21• Concatenating 79• Substrings 90
• Practice:Diamond 99• LiveSession 105
Page 100
100
String Diamond• Writeafunctiondiamond thatacceptsastringparameterandprintsitslettersina"diamond"formatasshownbelow.
• Forexample,diamond("DAISY") shouldprint:
DDADAIDAISDAISYAISYISYSYY
Page 101
101
String Diamond• Writeafunctiondiamond thatacceptsastringparameterandprintsitslettersina"diamond"formatasshownbelow.
• Forexample,diamond("DAISY") shouldprint:
DDADAIDAISDAISYAISYISYSYY
Page 103
103
Practice: Diamond
cp -r /afs/ir/class/cs107/lecture-code/lect4 .
Page 104
104
Recap• Characters• Strings• CommonStringOperations
• Comparing• Copying• Concatenating• Substrings
• Practice:Diamond
Nexttime:morestrings
Page 105
105
Additional Live Session Slides
Page 106
106
Plan For TodayFirst5minutes:postquestionsorcommentsonEdforwhatweshoulddiscuss
Lecture 4 takeaway: C strings are null-terminated arrays of characters. We can manipulate them using string and pointer operations.
Page 107
107
Key Takeaways
char str[6];strcpy(str, "Hello");int length = strlen(str); // 5printf("%s\n", str); // Hello
char *ptr = str + 1;printf("%s\n", ptr); // ello
0xf0 0xf1 0xf2 0xf3 0xf4 0xf5 address
'H' 'e' 'l' 'l' 'o' '\0' charstr
0xee
ptr
Page 108
108
char * vs. char[]• We’lltalkmoreaboutchar*vschar[]inlecture5• Someusefuldistinctionsinthemeantime:
• char*isan8-bytepointer– itstoresanaddressofacharacter• char[]isanarrayofcharacters– itstorestheactualcharactersinastring• Whenyoupassachar[]asaparameter,itisautomaticallypassedasachar*(pointertoitsfirstcharacter)
Page 109
109
Plan For TodayFirst5minutes:postquestionsorcommentsonEdforwhatweshoulddiscuss
Lecture 4 takeaway: C strings are null-terminated arrays of characters. We can manipulate them using string and pointer operations.
Page 110
110
String copying exercise
char buf[ 9 ];strcpy(buf, "Potatoes");printf("%s\n", buf);char *word = buf + 2;strncpy(word, "mat", 3);printf("%s\n", buf);
Line1:Whatvalueshouldgointheblank?
Line6:Whatisprinted?
123456
🤔
A. 7B. 8C. 9
A. matoesB. mattoesC. Pomat
D. 12E. strlen("Potatoes")F. Somethingelse
D. PomatoesE. SomethingelseF. Compileerror
____
Page 111
111
String copying exercise
char buf[ 9 ];strcpy(buf, "Potatoes");printf("%s\n", buf);char *word = buf + 2;strncpy(word, "mat", 3);printf("%s\n", buf);
Line1:Whatvalueshouldgointheblank?
Line6:Whatisprinted?
123456
A. 7B. 8C. 9
A. matoesB. mattoesC. Pomat
D. 12E. strlen("Potatoes")F. Somethingelse
D. PomatoesE. SomethingelseF. Compileerror
0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8
'P' 'o' 't' 'a' 't' 'o' 'e' 's' '\0'
0xf0
word
buf
Page 112
112
Copycat exerciseChallenge:implementstrcat usingotherstringfunctions.
char src[9];strcpy(src, "We Climb");char dst[200]; // lots of spacestrcpy(dst, "The Hill ");
strcat(dst, src);
🤔
Howcouldwereplaceacalltostrcat withacalltostrcpyinstead?
Page 113
113
Copycat exerciseChallenge:implementstrcat usingotherstringfunctions.
char src[9];strcpy(src, "We Climb");char dst[200]; // lots of spacestrcpy(dst, "The Hill ");
strcat(dst, src); strcpy(dst + strlen(dst), src);equivalent
Page 114
114
Initializing strings// create space for array first// then use string function to copy in contentchar buf1[6];strcpy(buf1, "hello");
// initialize array to exactly the size that fits// string + null terminatorchar buf2[] = "hello";
// will not work (why?)char buf3[6];buf3 = "hello";