58
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others. CS 106A, Lecture 9 Problem-Solving with Strings suggested reading: Java Ch. 8.5

CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

CS106A,Lecture9Problem-SolvingwithStrings

suggestedreading:JavaCh.8.5

Page 2: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

2

Learning Goals•Beabletowritestringalgorithmsthatoperateoneachcharacter.

•Beabletobuildupnewstringsfromexistingstringsusingbuilt-inStringmethods.

Page 3: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

3

Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher

Page 4: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

4

Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher

Page 5: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

5

Text Processing

Page 6: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

6

CharAchar isavariabletypethatrepresentsasinglecharacteror“glyph”.

char letterA = 'A';char plus = '+';char zero = '0';char space = ' ';char newLine = '\n';char tab = '\t';char singleQuote = '\'';char backSlash = '\\';

Page 7: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

7

CharUnderthehood,Javarepresentseachchar asaninteger (its“ASCIIvalue”).

•Uppercaselettersaresequentiallynumbered•Lowercaselettersaresequentiallynumbered•Digitsaresequentiallynumbered

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

Page 8: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

8

Char Math!WecantakeadvantageofJavarepresentingeachchar asaninteger (its“ASCIIvalue”):

boolean areEqual = 'A' == 'A'; // trueboolean earlierLetter = 'f' < 'c'; // falsechar uppercaseB = 'A' + 1;int diff = 'c' - 'a'; // 2int numLettersInAlphabet = 'z' – 'a' + 1;// orint numLettersInAlphabet = 'Z' – 'A' + 1;

Page 9: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

9

Side Note: Type-castingIfwewanttoforceJavatotreatanexpressionasaparticulartype,wecanalsocastit tothattype.

'A' + 1 // evaluates to 66 (int)(char)('A' + 1) // evaluates to 'B' (char)

1 / 2 // evaluates to 0 (int)(double)1 / 2 // evaluates to 0.5 (double)1 / (double)2 // evaluates to 0.5 (double)

Page 10: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

10

Character MethodsMethod Description

Character.isDigit(ch) trueifch is'0' through'9'

Character.isLetter(ch) trueifch is'a' through'z' or'A' through'Z'

Character.isLetterOrDigit(ch) trueifch is'a' through'z','A' through'Z' or '0' through'9'

Character.isLowerCase(ch) trueifch is'a' through'z'

Character.isUpperCase(ch) trueifch is'A' through'Z'

Character.toLowerCase(ch) returnslowercaseequivalentofaletter

Character.toUpperCase(ch) returnsuppercaseequivalentofaletter

Character.isWhitespace(ch) trueifch isaspace,tab,newline,etc.

Remember: these returnthe new char, they cannot modify an existing char!

Page 11: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

11

StringsAString isavariabletyperepresentingasequenceofcharacters.

String text = "Hi parents!";

– Eachcharacterisassignedanindex,goingfrom0tolength-1– Thereisachar ateachindex

index 0 1 2 3 4 5 6 7 8 9 10

character 'H' 'i' ' ' 'p' 'a' 'r' 'e' 'n' 't' 's' '!'

Page 12: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

12

Remember:charsandlength-1stringsaredifferent!

char ch = 'A' DIFFERENT FROM String str = "A"

Strings vs. Chars

Page 13: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

13

String str = "Hello, world!";String empty = "";println(str);

// Read in text from the userString name = readLine("What is your name? ");

// String concatenation (using “+”)String message = 2 + " cool " + 2 + " handle";int x = 2;println("x has the value " + x);

Creating Strings

Page 14: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

14

char c1 = 'a';char c2 = 'b';

// How do we concatenate these characters?

String str = c1 + c2; // ERROR: this is an int!

String str = "" + c1 + c2; // ✔

From Chars to Strings

Page 15: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

15

String MethodsMethodname Description

s.length() numberofcharactersinthisstring

s.charAt(index) charatthegivenindex

s.indexOf(str) indexwherethestartofthegivenstringappearsinthisstring(-1ifnotfound)

s.substring(index1, index2)ors.substring(index1)

thecharactersinthisstringfromindex1 (inclusive)toindex2 (exclusive);ifindex2 isomitted,goesuntilend

s.toLowerCase() anewstringwithalllowercaseletterss.toUpperCase() anewstringwithalluppercaseletters

• Thesemethodsarecalledusingdotnotation:

String className = "CS 106A yay!";println(className.length()); // 12

Page 16: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

16

SubstringsAsubstring isasubsetofastring.

String str = "Hello, world!";String hello = str.substring(0, 5);

0 1 2 3 4 5 6 7 8 9 10 11 12'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!'

Page 17: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

17

SubstringsAsubstring isasubsetofastring.

String str = "Hello, world!";String worldExclm = str.substring(7); // to end

0 1 2 3 4 5 6 7 8 9 10 11 12'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!'

Page 18: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

18

Comparing StringsMethod Description

s1.equals(s2) whethertwostringscontainthesamecharacters

s1.equalsIgnoreCase(s2) whethertwostringscontainthesamecharacters,ignoringuppervs.lowercase

s1.startsWith(s2) whethers1 containss2’scharactersatstart

s1.endsWith(s2) whethers1 containss2’scharactersatend

s1.contains(s2) whethers2 isfoundwithins1

Page 19: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

19

Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher

Page 20: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

20

Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.

String str = "Hello!";for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);// Do something with ch here

}

Page 21: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

21

Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.

// Prints out each letter on a separate lineString str = "Hello!";for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);println(ch);

}

Page 22: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

22

Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.

// Creates a new String in all capsString str = "Hello!";String newStr = "";for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);newStr = newStr + Character.toUpperCase(ch);

}println(newStr); // HELLO!

Page 23: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

23

Looping Over StringsAcommonStringprogrammingpatternisloopingoverastringandoperatingoneachcharacter.

// Creates a new String in all capsString str = "Hello!";String newStr = "";for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);newStr += Character.toUpperCase(ch);

}println(newStr); // HELLO!

Page 24: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

24

Building Up New StringsAnothercommonStringprogrammingpatternisbuildingupanewstringbyaddingcharacterstoitovertime.

// Creates a new String in all capsString str = "";for (int i = 0; i < 5; i++) {

str += i;}println(str); // 01234

Page 25: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

25

Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher

Page 26: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

26

Exercise: Reversing a StringLet’swriteamethodcalledreverseString thattakesoneStringparameter,andreturnsanewStringwiththecharactersintheoppositeorder.

reverseString("Hello!") -> "!olleH"

Page 27: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

27

H e l l o !

Reversing a String

Page 28: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

28

H e l l o !

!

Reversing a String

Page 29: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

29

H e l l o !

!

Reversing a String

Page 30: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

30

H e l l o !

! o

Reversing a String

Page 31: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

31

H e l l o !

! o

Reversing a String

Page 32: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

32

H e l l o !

! o l

Reversing a String

Page 33: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

33

H e l l o !

! o l

Reversing a String

Page 34: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

34

H e l l o !

! o l l

Reversing a String

Page 35: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

35

H e l l o !

! o l l

Reversing a String

Page 36: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

36

H e l l o !

! o l l e

Reversing a String

Page 37: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

37

H e l l o !

! o l l e

Reversing a String

Page 38: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

38

H e l l o !

! o l l e H

Reversing a String

Page 39: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

39

H e l l o !

! o l l e H

Reversing a String

Page 40: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

40

Reversing a StringString str = "Hello!";String newStr = "";for (??? ; ??? ; ???) {

...}

Page 41: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

41

Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; ??? ; ???) {

...}

H e l l o !

!

Page 42: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

42

Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; i >= 0; ???) {

...}

! o l l e H

H e l l o !

Page 43: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

43

Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; i >= 0; i--) {

...}

! o l l e H

H e l l o !

Page 44: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

44

Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; i >= 0; i--) {

newStr += str.charAt(i);}

Page 45: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

45

H e l l o !

Reversing a String

Page 46: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

46

H e l l o !

H

Reversing a String

Page 47: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

47

H e l l o !

He

Reversing a String

Page 48: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

48

H e l l o !

Hel

Reversing a String

Page 49: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

49

H e l l o !

Hell

Reversing a String

Page 50: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

50

H e l l o !

Hello

Reversing a String

Page 51: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

51

H e l l o !

Hello!

Reversing a String

Page 52: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

52

Reversing a Stringpublic void run() {

println("This program reverses a string.");String str = readLine("Enter a string: ");String rev = reverseString(str);println(str + " spelled backwards is " + rev);

}

ReverseString

str

STRESSED

This program reverses a string.

STRESSED spelled backwards is DESSERTSSTRESSEDEnter a string:

rev

DESSERTS

private String reverseString(String str) {String result = "";for ( int i = 0; i < str.length(); i++ ) {

result = str.charAt(i) + result;}return result;

}

istrresult

STRESSED 012345678STSRTSERTSSERTSSSERTSESSERTSDESSERTS

Using portions of slides by Eric Roberts

Page 53: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

53

Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher

Page 54: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

54

Exercise: PalindromesLet’swriteamethodcalledisPalindrome thattakesoneStringparameter,andreturnswhetherornotthatStringisapalindrome(thesameforwardsandbackwards).

isPalindrome("racecar") -> trueisPalindrome("hi there") -> falseisPalindrome("kayak") -> true

Page 55: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

55

Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher

Page 56: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

56

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

D E F G H I J K L M N O P Q R S T U V W X Y Z A B C

• Rotatealphabetbyn letters(n =3inbelow)– n iscalledthekey

• Wrap-aroundattheend

• Substitutelettersbasedonthismapping

original

encrypt

Exercise: Caesar Cipher

Page 57: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

57

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

D E F G H I J K L M N O P Q R S T U V W X Y Z A B C

• Rotatealphabetbyacertainkey,withwrapping

original

encrypt

Exercise: Caesar Cipher

Page 58: CS 106A, Lecture 9 - Stanford Universityweb.stanford.edu/class/archive/cs/cs106a/cs106a...15 String Methods Method name Description s.length() number of characters in this string s.charAt(index)

58

Recap•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher

Nexttime:readingtextfiles