CS 106A, Lecture 9 Problem-Solving with Strings

Similar documents
CS 106A, Lecture 9 Problem-Solving with Strings

CS107 Spring 2019, Lecture 4 C Strings

CS107, Lecture 4 C Strings

CS106A Review Session

char ch = astring; //where astring is a String..illegal char ch = A ; //illegal

An Interesting Article. How Revolutionary Tools Cracked a 1700s Code.

Programming Lecture 9

CS 106A, Lecture 19 ArrayLists

CS 106A, Lecture 27 Final Exam Review 1

CS 106A, Lecture 27 Final Exam Review 1

Programming Lecture 9

Building Java Programs

CS 106A, Lecture 7 Parameters and Return

CS 106A, Lecture 16 Arrays

AP Computer Science A

CS 106X, Lecture 16 More Linked Lists

CS 106A, Lecture 5 Booleans and Control Flow

CS106A Review Session. Monday Oct. 31, 2016 Nick Troccoli

CS 106A, Lecture 20 ArrayLists and HashMaps

"Hello" " This " + "is String " + "concatenation"

CS 106A, Lecture 14 Events and Instance Variables

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

October 27, 7:30-9:30 PM Taylor Bacon and Kashif Nazir (Based on slides by Nick Troccoli)

The second statement selects character number 1 from and assigns it to.

Memory Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Eng. Mohammed Abdualal

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

CS 106A, Lecture 3 Problem-solving with Karel

Lab #7 Library Classes and JUnit Testing. Daniel Amyot, Diana Inkpen, Alan. Agenda. In this lab, you are going to create your own

CS 106X, Lecture 10 Recursive Backtracking

CS 106A, Lecture 3 Problem-solving with Karel

Lecture 8: The String Class and Boolean Zen

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Solution to Section #3 Portions of this handout by Eric Roberts, Mehran Sahami, Marty Stepp, Patrick Young and Jeremy Keeshin

Lecture 19: Recursion

CS 106A, Lecture 14 Events and Instance Variables

Creating Strings. String Length

CS 106A, Lecture 25 Life After CS 106A, Part 1

CS 106B, Lecture 1 Introduction to C++

Strings. Steven R. Bagley

CSE 2123 Recursion. Jeremy Morris

CSc 110, Spring Lecture 14: Booleans and Strings. Adapted from slides by Marty Stepp and Stuart Reges

CS 1301 Ch 8, Part A

Section Handout #3: Strings and Files

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017

CS106A Final Exam Review Session. Saturday Dec. 10, 2016 Nick Troccoli

CSc 110, Autumn Lecture 14: Strings. Adapted from slides by Marty Stepp and Stuart Reges

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

CS 106A, Lecture 11 Graphics

Chapter 4. Mathematical Functions, Characters, and Strings

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 106X, Lecture 7 Introduction to Recursion

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

CS 106A, Lecture 23 Interactors and GCanvas

t 1 =2 t n =3t n 1 1,n 1

Hangman YEAH Hours. Thursday, February 14, 7:30 9:00PM Andrew Tierno

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

COMP-202: Foundations of Programming. Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016

Introducing arrays. Week 4: arrays and strings. Creating arrays. Declaring arrays. Initialising arrays. Declaring and creating in one step

Chapter 7 User-Defined Methods. Chapter Objectives

Variables, Constants, and Data Types

Homework Assignment 2: Java Console and Graphics

Intro to Strings. CSE 231 Rich Enbody. String: a sequence of characters. Indicated with quotes: or " " 9/11/13

CS 106 Introduction to Computer Science I

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

CSC 222: Object-Oriented Programming. Spring 2017

Using System.out.println()

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

You ll be reading more about tools for branching in Sections 3.4, and We are skipping Sections 3.5, 3.11 and 3.13-end of chapter.

x++ vs. ++x x=y++ x=++y x=0; a=++x; b=x++; What are the values of a, b, and x?

CSc 110, Autumn Lecture 11: Strings. Adapted from slides by Marty Stepp and Stuart Reges

Topic 13 procedural design and Strings

CS 106X, Lecture 14 Classes and Pointers

String related classes

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

Getting started with Java

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

ENGR/CS 101 CS Session Lecture 3

String Objects: The string class library

Notes from the Boards Set BN19 Page

Lecture 2: Variables & Assignments

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

STRINGS AND STRINGBUILDERS. Spring 2019

Simple Arrays. Eric Roberts CS 106A February 15, 2017

The data in the table are arranged into 12 rows and 12 columns. The process of printing them out can be expressed in a pseudocode algorithm as

CS 106X, Lecture 23 Dijkstra and A* Search

CS 2316 Pair 1: Homework 3 Enigma Fun Due: Wednesday, February 1st, before 11:55 PM Out of 100 points

CSC 222: Object-Oriented Programming. Spring 2013

CMPT 125: Lecture 3 Data and Expressions

Unit 2: The string class

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Transcription:

CS 106A, Lecture 9 Problem-Solving with Strings suggested reading: Java Ch. 8.5 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.

Plan For Today Announcements Recap: Characters and Strings More Strings Practice: Reversing a String Practice: Palindromes Practice: Caesar Cipher 2

Plan For Today Announcements Recap: Characters and Strings More Strings Practice: Reversing a String Practice: Palindromes Practice: Caesar Cipher 3

Announcements Assignment 2 is due tomorrow! Please submit ahead of time, just in case Questions during lecture: Keep asking! I will start directing some to Piazza J 4

Plan For Today Announcements Recap: Characters and Strings More Strings Practice: Reversing a String Practice: Palindromes Practice: Caesar Cipher 5

Char A char is a variable type that represents a single character or glyph. char lettera = 'A'; char plus = '+'; char zero = '0'; char space = ' '; char newline = '\n'; char tab = '\t'; char singlequote = '\''; char backslash = '\\'; 6

Char Under the hood, Java represents each char as an integer (its ASCII value ). Uppercase letters are sequentially numbered Lowercase letters are sequentially numbered Digits are sequentially numbered char uppercasea = 'A'; // Actually 65 char lowercasea = 'a'; // Actually 97 char zerodigit = '0'; // Actually 48 7

Char Math! We can take advantage of Java representing each char as an integer (its ASCII value ): boolean areequal = 'A' == 'A'; // true boolean earlierletter = 'f' < 'c'; // false char uppercaseb = 'A' + 1; int diff = 'c' - 'a'; // 2 int numlettersinalphabet = 'z' 'a' + 1; // or int numlettersinalphabet = 'Z' 'A' + 1; 8

Side Note: Type-casting If we want to force Java to treat an expression as a particular type, we can also cast it to that type. 'A' + 1 (char)('a' + 1) // evaluates to 66 (int) // 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) 9

Character Methods Method Character.isDigit(ch) Character.isLetter(ch) Character.isLetterOrDigit(ch) Character.isLowerCase(ch) Character.isUpperCase(ch) Character.toLowerCase(ch) Character.toUpperCase(ch) Character.isWhitespace(ch) Description true if ch is '0' through '9' true if ch is 'a' through 'z' or 'A' through 'Z' true if ch is 'a' through 'z', 'A' through 'Z' or '0' through '9' true if ch is 'a' through 'z' true if ch is 'A' through 'Z' returns lowercase equivalent of a letter returns uppercase equivalent of a letter true if ch is a space, tab, new line, etc. Remember: tolowercase and touppercase return the new char; they cannot modify an existing char! 10

Strings A String is a variable type representing a sequence of characters. String text = "Hi parents!"; index 0 1 2 3 4 5 6 7 8 9 10 character 'H' 'i' ' ' 'p' 'a' 'r' 'e' 'n' 't' 's' '!' Each character is assigned an index, going from 0 to length-1 There is a char at each index 11

Strings vs. Chars Remember: chars and length-1 strings are different! char ch = 'A' DIFFERENT FROM String str = A 'A' + 1 A + 1 // evaluates to 66 (int) // evaluates to A1 (String) 12

Creating Strings String str = "Hello, world!"; String empty = ""; println(str); // Read in text from the user String name = readline("what is your name? "); // String concatenation (using + ) String message = name + " is " + 2 + " cool."; 13

From Chars to Strings 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; // 14

Plan For Today Announcements Recap: Characters and Strings More Strings Practice: Reversing a String Practice: Palindromes Practice: Caesar Cipher 15

Substrings A substring is a subset of a string. 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' '!' 16

Substrings A substring is a subset of a string. String str = "Hello, world!"; String worldexclm = str.substring(7, 13); 0 1 2 3 4 5 6 7 8 9 10 11 12 'H' 'e' 'l' 'l' 'o' ',' ' ' 'w' 'o' 'r' 'l' 'd' '!' 17

Substrings A substring is a subset of a string. 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' '!' 18

String Methods s.length() Method name s.charat(index) s.indexof(str) s.substring(index1, index2) or s.substring(index1) s.tolowercase() s.touppercase() Description number of characters in this string char at the given index index where the start of the given string appears in this string (-1 if not found) the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, goes until end a new string with all lowercase letters a new string with all uppercase letters These methods are called using dot notation: String classname = "CS 106yay!"; println(classname.length()); // 10 19

Strings are Immutable Once you create a String, its contents cannot be changed. // Cannot change individual chars in the string String typo = "Hello, warld! ; typo.charat(8) = o ; // Error! Will not run. To change a String, you must create a new String containing the value you want (possibly using String methods). String corrected = typo.substring(0, 8) + o + typo.substring(9); 20

Strings are Immutable String classname = "cs 106a"; classname.touppercase(); // does nothing! classname = classname.touppercase(); // println(classname); // CS 106A 21

Comparing Strings String greeting = Hello! ; if (greeting == "Hello!") {... } // Doesn t work! // Instead: if (greeting.equals("hello!")) {... } Always use.equals instead of == and!= 22

Comparing Strings Method s1.equals(s2) s1.equalsignorecase(s2) s1.startswith(s2) s1.endswith(s2) s1.contains(s2) Description whether two strings contain the same characters whether two strings contain the same characters, ignoring upper vs. lower case whether s1 contains s2 s characters at start whether s1 contains s2 s characters at end whether s2 is found within s1 23

Looping Over Strings A common String programming pattern is looping over a string and operating on each character. String str = "Hello!"; for (int i = 0; i < str.length(); i++) { char ch = str.charat(i); // Do something with ch here } 24

Looping Over Strings A common String programming pattern is looping over a string and operating on each character. // Prints out each letter on a separate line String str = "Hello!"; for (int i = 0; i < str.length(); i++) { char ch = str.charat(i); println(ch); } 25

Looping Over Strings A common String programming pattern is looping over a string and operating on each character. // Creates a new String in all caps String 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! 26

Looping Over Strings A common String programming pattern is looping over a string and operating on each character. // Creates a new String in all caps String str = "Hello!"; String newstr = ""; for (int i = 0; i < str.length(); i++) { char ch = str.charat(i); newstr += Character.toUpperCase(ch); } println(newstr); // HELLO! 27

Building Up New Strings Another common String programming pattern is building up a new string by adding characters to it over time. // Creates a new String in all caps String str = ""; for (int i = 0; i < 5; i++) { str += i; } println(str); // 01234 28

Plan For Today Announcements Recap: Characters and Strings More Strings Practice: Reversing a String Practice: Palindromes Practice: Caesar Cipher 29

Exercise: Reversing a String Let s write a method called reversestring that takes one String parameter, and returns a new String with the characters in the opposite order. reversestring("hello!") -> "!olleh" 30

Reversing a String H e l l o! 31

Reversing a String H e l l o!! 32

Reversing a String H e l l o!! 33

Reversing a String H e l l o!! o 34

Reversing a String H e l l o!! o 35

Reversing a String H e l l o!! o l 36

Reversing a String H e l l o!! o l 37

Reversing a String H e l l o!! o l l 38

Reversing a String H e l l o!! o l l 39

Reversing a String H e l l o!! o l l e 40

Reversing a String H e l l o!! o l l e 41

Reversing a String H e l l o!! o l l e H 42

Reversing a String H e l l o!! o l l e H 43

Reversing a String String str = "Hello!"; String newstr = ""; for (??? ;??? ;???) {... } 44

Reversing a String String str = "Hello!"; String newstr = ""; for (int i = str.length() - 1;??? ;???) {... } H e l l o!! 45

Reversing a String String str = "Hello!"; String newstr = ""; for (int i = str.length() - 1; i >= 0;???) {... } H e l l o!! o l l e H 46

Reversing a String String str = "Hello!"; String newstr = ""; for (int i = str.length() - 1; i >= 0; i--) {... } H e l l o!! o l l e H 47

Reversing a String String str = "Hello!"; String newstr = ""; for (int i = str.length() - 1; i >= 0; i--) { newstr += str.charat(i); } 48

Reversing a String H e l l o! 49

Reversing a String H e l l o! H 50

Reversing a String H e l l o! e H 51

Reversing a String H e l l o! l e H 52

Reversing a String H e l l o! l l e H 53

Reversing a String H e l l o! o l l e H 54

Reversing a String H e l l o!! o l l e H 55

Reversing a String public void run() { private println("this String reversestring(string program reverses a string."); str) { String String str result = readline("enter = ""; a string: "); String for ( rev int = i reversestring(str); = 0; i < str.length(); i++ ) { println(str result = + str.charat(i) " spelled backwards + result; is " + rev); } } return result; rev } DESSERTS str STRESSED result str i STS SERTS DESSERTS STRESSED 012345678 ReverseString This program reverses a string. Enter a string: STRESSED STRESSED spelled backwards is DESSERTS Using portions of slides by Eric Roberts 56

Plan For Today Announcements Recap: Characters and Strings More Strings Practice: Reversing a String Practice: Palindromes Practice: Caesar Cipher 57

Exercise: Palindromes Let s write a method called ispalindrome that takes one String parameter, and returns whether or not that String is a palindrome (the same forwards and backwards). ispalindrome("racecar") -> true ispalindrome("hi there") -> false ispalindrome("kayak") -> true 58

Plan For Today Announcements Recap: Characters and Strings More Strings Practice: Reversing a String Practice: Palindromes Practice: Caesar Cipher 59

Exercise: Caesar Cipher Rotate alphabet by n letters (n = 3 in below) n is called the key Wrap-around at the end Substitute letters based on this mapping original encrypt 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 60

Exercise: Caesar Cipher Rotate alphabet by a certain key, with wrapping original encrypt 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 61

Recap Recap: Characters and Strings More Strings Practice: Reversing a String Practice: Palindromes Practice: Caesar Cipher Next time: reading text files 62