Page 1
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture9Problem-SolvingwithStrings
suggestedreading:JavaCh.8.5
Page 2
2
Learning Goals•Beabletowritestringalgorithmsthatoperateoneachcharacter.
•Beabletobuildupnewstringsfromexistingstringsusingbuilt-inStringmethods.
Page 3
3
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
Page 4
4
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
Page 6
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
7
CharUnderthehood,Javarepresentseachchar asaninteger (its“ASCIIvalue”).
•Uppercaselettersaresequentiallynumbered•Lowercaselettersaresequentiallynumbered•Digitsaresequentiallynumbered
char uppercaseA = 'A'; // Actually 65char lowercaseA = 'a'; // Actually 97char zeroDigit = '0'; // Actually 48
Page 8
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
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
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
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
12
Remember:charsandlength-1stringsaredifferent!
char ch = 'A' DIFFERENT FROM String str = "A"
Strings vs. Chars
Page 13
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
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
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
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
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
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
19
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
Page 20
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
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
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
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
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
25
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
Page 26
26
Exercise: Reversing a StringLet’swriteamethodcalledreverseString thattakesoneStringparameter,andreturnsanewStringwiththecharactersintheoppositeorder.
reverseString("Hello!") -> "!olleH"
Page 27
27
H e l l o !
Reversing a String
Page 28
28
H e l l o !
!
Reversing a String
Page 29
29
H e l l o !
!
Reversing a String
Page 30
30
H e l l o !
! o
Reversing a String
Page 31
31
H e l l o !
! o
Reversing a String
Page 32
32
H e l l o !
! o l
Reversing a String
Page 33
33
H e l l o !
! o l
Reversing a String
Page 34
34
H e l l o !
! o l l
Reversing a String
Page 35
35
H e l l o !
! o l l
Reversing a String
Page 36
36
H e l l o !
! o l l e
Reversing a String
Page 37
37
H e l l o !
! o l l e
Reversing a String
Page 38
38
H e l l o !
! o l l e H
Reversing a String
Page 39
39
H e l l o !
! o l l e H
Reversing a String
Page 40
40
Reversing a StringString str = "Hello!";String newStr = "";for (??? ; ??? ; ???) {
...}
Page 41
41
Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; ??? ; ???) {
...}
H e l l o !
!
Page 42
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
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
44
Reversing a StringString str = "Hello!";String newStr = "";for (int i = str.length() - 1; i >= 0; i--) {
newStr += str.charAt(i);}
Page 45
45
H e l l o !
Reversing a String
Page 46
46
H e l l o !
H
Reversing a String
Page 47
47
H e l l o !
He
Reversing a String
Page 48
48
H e l l o !
Hel
Reversing a String
Page 49
49
H e l l o !
Hell
Reversing a String
Page 50
50
H e l l o !
Hello
Reversing a String
Page 51
51
H e l l o !
Hello!
Reversing a String
Page 52
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
53
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
Page 54
54
Exercise: PalindromesLet’swriteamethodcalledisPalindrome thattakesoneStringparameter,andreturnswhetherornotthatStringisapalindrome(thesameforwardsandbackwards).
isPalindrome("racecar") -> trueisPalindrome("hi there") -> falseisPalindrome("kayak") -> true
Page 55
55
Plan For Today•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
Page 56
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
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
58
Recap•Recap:CharactersandStrings•LoopingoverStrings•Practice:ReversingaString•Practice:Palindromes•Practice:CaesarCipher
Nexttime:readingtextfiles