Top Banner
1 This document is copyright (C) Stanford Computer Science, Lisa Yan, and Nick Troccoli, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Marty Stepp, Cynthia Lee, Chris Gregg, Lisa Yan, Jerry Cain and others. CS107, Lecture 4 C Strings Reading: K&R (1.9, 5.5, Appendix B3) or Essential C section 3
114

CS107, Lecture 4

Jan 17, 2022

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS107, Lecture 4

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: CS107, Lecture 4

2

CS107 Topic 2: How can a computer represent and

manipulate more complex data like text?

Page 3: CS107, Lecture 4

3

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

• Comparing 19• Copying 21• Concatenating 79• Substrings 90

• Practice:Diamond 99• LiveSession 105

Page 4: CS107, Lecture 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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

8

ASCIIWecantakeadvantageofCrepresentingeachchar asaninteger:

// prints out every lowercase characterfor (char ch = 'a'; ch <= 'z'; ch++) {

printf("%c", ch);

}

Page 9: CS107, Lecture 4

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: CS107, Lecture 4

10

Common ctype.h Functionsbool isLetter = isalpha('A'); // truebool capital = isupper('f'); // falsechar uppercaseB = toupper('b');

bool isADigit = isdigit('4'); // true

Page 11: CS107, Lecture 4

11

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

• Comparing 19• Copying 21• Concatenating 79• Substrings 90

• Practice:Diamond 99• LiveSession 105

Page 12: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

14

C Strings As ParametersWhenwepassastringasaparameter,itispassedasachar*.Cpassesthelocationofthefirstcharacterratherthanacopyofthewholearray.int doSomething(char *str) {

...}

char myString[6];...doSomething(myString);

Page 15: CS107, Lecture 4

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: CS107, Lecture 4

16

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

• Comparing 19• Copying 21• Concatenating 79• Substrings 90

• Practice:Diamond 99• LiveSession 105

Page 17: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

24

Copying Strings - strcpyWemustmakesurethereisenoughspaceinthedestinationtoholdtheentirecopy,includingthenull-terminatingcharacter.

char str2[6]; // not enough space!strcpy(str2, "hello, world!"); // overwrites other memory!

Writingpastmemoryboundsiscalleda“bufferoverflow”.Itcanallowforsecurityvulnerabilities!

Page 25: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

77

String Copying ExerciseWhatvalueshouldgointheblankatright?A. 4B. 5C. 6D. 12E. strlen(“hello”)F. Somethingelse

char str[______];strcpy(str, "hello");

Page 78: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

99

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

• Comparing 19• Copying 21• Concatenating 79• Substrings 90

• Practice:Diamond 99• LiveSession 105

Page 100: CS107, Lecture 4

100

String Diamond• Writeafunctiondiamond thatacceptsastringparameterandprintsitslettersina"diamond"formatasshownbelow.

• Forexample,diamond("DAISY") shouldprint:

DDADAIDAISDAISYAISYISYSYY

Page 101: CS107, Lecture 4

101

String Diamond• Writeafunctiondiamond thatacceptsastringparameterandprintsitslettersina"diamond"formatasshownbelow.

• Forexample,diamond("DAISY") shouldprint:

DDADAIDAISDAISYAISYISYSYY

Page 102: CS107, Lecture 4

102

Daisy!

Page 103: CS107, Lecture 4

103

Practice: Diamond

cp -r /afs/ir/class/cs107/lecture-code/lect4 .

Page 104: CS107, Lecture 4

104

Recap• Characters• Strings• CommonStringOperations

• Comparing• Copying• Concatenating• Substrings

• Practice:Diamond

Nexttime:morestrings

Page 105: CS107, Lecture 4

105

Additional Live Session Slides

Page 106: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

108

char * vs. char[]• We’lltalkmoreaboutchar*vschar[]inlecture5• Someusefuldistinctionsinthemeantime:

• char*isan8-bytepointer– itstoresanaddressofacharacter• char[]isanarrayofcharacters– itstorestheactualcharactersinastring• Whenyoupassachar[]asaparameter,itisautomaticallypassedasachar*(pointertoitsfirstcharacter)

Page 109: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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: CS107, Lecture 4

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";