cs107, lecture 4

114
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

Upload: others

Post on 17-Jan-2022

1 views

Category:

Documents


0 download

TRANSCRIPT

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

2

CS107 Topic 2: How can a computer represent and

manipulate more complex data like text?

3

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

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

• Practice:Diamond 99• LiveSession 105

4

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

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

• Practice:Diamond 99• LiveSession 105

5

CharAchar isavariabletypethatrepresentsasinglecharacteror“glyph”.

char letterA = 'A';

char plus = '+';

char zero = '0';

char space = ' ';

char newLine = '\n';

char tab = '\t';

char singleQuote = '\'';

char backSlash = '\\';

6

ASCIIUnderthehood,Crepresentseachchar asaninteger (its“ASCIIvalue”).

• Uppercaselettersaresequentiallynumbered• Lowercaselettersaresequentiallynumbered• Digitsaresequentiallynumbered• Lowercaselettersare32morethantheiruppercaseequivalents(bitflip!)

char uppercaseA = 'A'; // Actually 65char lowercaseA = 'a'; // Actually 97char zeroDigit = '0’; // Actually 48

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;

8

ASCIIWecantakeadvantageofCrepresentingeachchar asaninteger:

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

printf("%c", ch);

}

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

10

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

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

11

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

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

• Practice:Diamond 99• LiveSession 105

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'

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.

14

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

...}

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

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[].

16

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

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

• Practice:Diamond 99• LiveSession 105

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.

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.

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.

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}

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.

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

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'

? ? ? ? ? ?

24

Copying Strings - strcpyWemustmakesurethereisenoughspaceinthedestinationtoholdtheentirecopy,includingthenull-terminatingcharacter.

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

Writingpastmemoryboundsiscalleda“bufferoverflow”.Itcanallowforsecurityvulnerabilities!

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-

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'

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'!

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'

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'

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'

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'

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'

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'

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'

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-

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-

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-

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-

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-

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-

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-

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-

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-

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-

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

? ? ? ? ? ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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' ? ? ? ? ? ? ? ? ?

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⍰⍰⍰

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

77

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

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

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

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.

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.

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' ? ? ? ? ? ?

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'

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'

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'

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'

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'

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'

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'

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'

90

Substrings and char *Youcanalsocreateachar*variableyourselfthatpointstoanaddresswithininanexistingstring.

char myString[3]; myString[0] = 'H';myString[1] = 'i';myString[2] = '\0';

char *otherStr = myString; // points to 'H'

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

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

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

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

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

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

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

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

99

Lecture Plan• Characters 4• Strings 11• CommonStringOperations 16

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

• Practice:Diamond 99• LiveSession 105

100

String Diamond• Writeafunctiondiamond thatacceptsastringparameterandprintsitslettersina"diamond"formatasshownbelow.

• Forexample,diamond("DAISY") shouldprint:

DDADAIDAISDAISYAISYISYSYY

101

String Diamond• Writeafunctiondiamond thatacceptsastringparameterandprintsitslettersina"diamond"formatasshownbelow.

• Forexample,diamond("DAISY") shouldprint:

DDADAIDAISDAISYAISYISYSYY

102

Daisy!

103

Practice: Diamond

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

104

Recap• Characters• Strings• CommonStringOperations

• Comparing• Copying• Concatenating• Substrings

• Practice:Diamond

Nexttime:morestrings

105

Additional Live Session Slides

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.

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

108

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

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

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.

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

____

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

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?

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

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