Lecture 8: The String class

Slides:



Advertisements
Similar presentations
Java Programming Strings Chapter 7.
Advertisements

Building Java Programs
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-3: Strings and objects; printf reading: 3.3, self-check: Ch.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Topic 13 procedural design and Strings Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
1 Text Processing. 2 Type char char : A primitive type representing single characters. –A String is stored internally as an array of char String s = "Ali.
1 Sierpinski Valentine. CS 112 Introduction to Programming Switch; Text Processing Yang (Richard) Yang Computer Science Department.
Objects and Classes; Strings. 2 Classes and objects class: A program entity that represents either 1.A program / module, or 2.A type of objects* –A class.
1 Text processing. 2 text processing: Examining, editing, formatting text.  Text processing often involves for loops that examine the characters of a.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 10/27/20151.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 5/27/20161.
1 BUILDING JAVA PROGRAMS CHAPTER 3 THE STRING CLASS.
1 Text processing Readings: Characters char : A primitive type representing single characters. Individual characters inside a String are stored.
Do/while Loops Another Type of Indefinite Loop. 2 The do/while loop do/while loop: Performs its test at the end of each repetition. –Guarantees that the.
1 BUILDING JAVA PROGRAMS CHAPTER 3 THE STRING CLASS.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers; Type boolean reading: , 5.6.
CHAPTER 6 GC Strings. THE CLASS STRING  Contains operations to manipulate strings.  String:  Sequence of zero or more characters.  Enclosed.
CS 112 Introduction to Programming Boolean Type, String Processing Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, 4.3.
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
Topic 15 boolean methods and random numbers
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Building Java Programs
Building Java Programs
Building Java Programs
Adapted from slides by Marty Stepp and Stuart Reges
Building Java Programs
Building Java Programs Chapter 4
Building Java Programs
CSCI 161 – Introduction to Programming I William Killian
Building Java Programs
Chapter 6 GC 101 Strings.
Adapted from slides by Marty Stepp and Stuart Reges
Conditional Execution
Strings string: An object storing a sequence of text characters.
Lecture 4: Conditionals
Topic 13 procedural design and Strings
Java Strings Slides provided by the University of Washington Computer Science & Engineering department.
Topic 15 boolean methods and random numbers
Building Java Programs
Building Java Programs
תרגול מס' 3 עבודה עם מחרוזות (Strings) מתודות (Methods) העברת פרמטרים
Building Java Programs
Adapted from slides by Marty Stepp and Stuart Reges
CSc 110, Spring 2018 Lecture 14: Booleans and Strings
Building Java Programs
Building Java Programs
Lecture 8: The String Class and Boolean Zen
Building Java Programs
Building Java Programs
Lecture 14: Strings and Recursion AP Computer Science Principles
Building Java Programs
Using Objects (continued)
Building Java Programs
Building Java Programs
String methods 26-Apr-19.
Boolean logic suggested reading: 5.2.
Building Java Programs
Building Java Programs
Strings string: An object storing a sequence of text characters.
Building Java Programs Chapter 4
Building Java Programs
Presentation transcript:

Lecture 8: The String class Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved.

Strings string: An object storing a sequence of text characters. String is not a primitive type. String is an object type. Unlike most other objects, a String is not created with new. Scanner input = new Scanner(System.in); String name = "text"; String name2 = expression; Examples: String name = "Marla Singer"; int x = 3; int y = 5; String point = "(" + x + ", " + y + ")"; // (3, 5)

Indexes Characters of a string are numbered with 0-based indexes: String name = "R. Kelly"; First character's index : 0 Last character's index : 1 less than the string's length The individual characters are values of type char index 1 2 3 4 5 6 7 character R . K e l y

String methods These methods are called using the dot notation: String gangsta = "Dr. Dre"; System.out.println(gangsta.length()); // 7 Method name Description indexOf(str) Returns index where the start of the given string appears in this string (-1 if not found) length() Returns number of characters in this string substring(index1, index2) or substring(index1) Returns the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string toLowerCase() Returns a new string with all lowercase letters toUpperCase() Returns a new string with all uppercase letters

String method examples // index 012345678901 String s1 = "Stuart Reges"; String s2 = "Marty Stepp"; System.out.println(s1.length()); // 12 System.out.println(s1.indexOf("e")); // 8 System.out.println(s1.substring(7, 10)); // "Reg" System.out.println(s1.substring(2));// ”uart Reges” System.out.println(s1.substring(2,3));// ”u” System.out.println(s1.substring(2,2));// ”” empty str String s3 = s2.substring(1, 7); // "arty S” System.out.println(s3.toLowerCase()); // "arty s” Given the following string: // index 0123456789012345678901 String book = "Building Java Programs"; How would you extract the word "Java" ? String word=book.substring(9,13);

Modifying strings Methods like substring and toLowerCase build and return a new string, rather than modifying the current string. String s = "lil bow wow"; s.toUpperCase(); System.out.println(s); // lil bow wow To modify a variable's value, you must reassign it: s = s.toUpperCase(); System.out.println(s); // LIL BOW WOW

String test methods Method Description String name = console.next(); if (name.contains("Prof")) { System.out.println("When are your office hours?"); } Method Description equals(str) whether two strings contain the same characters equalsIgnoreCase(str) whether two strings contain the same characters, ignoring upper vs. lower case contains(str) whether the given string is found within this one startsWith(str) whether the given string starts with this one endsWith(str) whether the given string ends with this one

Methods that are tests Some methods return logical values. A call to such a method is used as a test in a loop or if. Scanner console = new Scanner(System.in); System.out.print("Type your name: "); String name = console.nextLine(); if (name.startsWith("Dr.")) { System.out.println("Will you marry me?"); } else if (name.endsWith("Esq.")) { System.out.println("And I am Ted 'Theodore' Logan!"); }

Comparing strings Relational operators such as < and == fail on objects. Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); if (name == "Barney") { System.out.println("I love you, you love me,"); System.out.println("We're a happy family!"); } This code will compile, but it will not print the song. The variable name and the literal string “Barney” are two different Strings even though they have the same characters. == compares objects by references (seen later), so it often gives false even when two Strings have the same letters.

The equals method Objects are compared using a method named equals. Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); if (name.equals(“Barney”)) { System.out.println("I love you, you love me,"); System.out.println("We're a happy family!"); } Technically this is a method that returns a value of type boolean, the type used in logical tests.

Lab 1: Gangsta Name Write a program that outputs a person's "gangsta name." first initial Diddy last name (all caps) first name -izzle Example Output: Type your name, playa: Marge Simpson Your gangsta name is M. Diddy SIMPSON Marge-izzle “Why did Snoop Dog bring an umbrella?” “For drizzle”

Some String Properties String substring(int index1, int index2) There is an IndexOutOfBoundsException if a) index1 is negative b) index2 is larger than the length of the string or c) index1 is larger than index2. String s=“strawberry”; int x; String a; x=s.length(); // 10 a=s.substring(5,9) // “berr” a=s.substring(5,10) // “berry” a=s.substring(5,11) // IndexOutOfBoundsException a=s.substring(6,5) // IndexOutOfBoundsException

Some String Properties int indexOf(String str) Returns index of first letter of first occurrence of str within this string. Returns -1 if not found. Error if str is null. String a=“”; // a is empty string String b; // b is null String c=“happy”; int x= c.indexOf(“ppy”); //x has value 2 x=c.indexOf(“hi”); //x now has value -1 x=c.indexOf(b); // error x=c.indexOf(a); // x is 0 // since e.g “” + “abc” = “abc”

Some String Properties String substring(int index) There is an IndexOutOfBoundsException if index is negative or larger than the length of the string. String s=“cold”,b; b=s.substring(3); // b=“d”; b=“cold”.substring(4); // b=“”, the empty string b=s.substring(5); //IndexOutOfBoundsException b=“cold”.substring(-3);//IndexOutOfBoundsException

Substring Methods On the AP exam, only the following methods will be tested. Although there are a lot more useful methods in the String class, try to use only these in your programming projects. length() indexOf(String a) substring(int index) substring(int index1, int index2) equals(String a)

Lab 2: Parsing Write a method parseAddress that takes a String parameter representing an address and prints out each component of the address. Assume that the parameter has the exact format as the example below. parseAddress(“123 Adams st Dorchester, MA 02122”); Should print out: Number: 123 Street: Adams st City/State: Dorchester, MA Zip code: 02122 Hint: Find the location of each space and extract.