appreciate the difference between a char and a string understand and use the String class methods

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

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

STUDENT LESSON A10 The String Class

Lab 14 & 15: String Handling

More on variables and methods

AP Computer Science. Strings. Credit: Slides are modified with permission from Barry Wittman at Elizabethtown College

Creating Strings. String Length

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings

CS112 Lecture: Characters and Strings

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

The student should be familiar with classes, boolean and String fields, relational operators, parameters and arguments.

String. Other languages that implement strings as character arrays

CHAPTER 6 MOST COMMONLY USED LIBRARIES

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

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

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

Object-Oriented Programming

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

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

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

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

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

Programming with Java

Eng. Mohammed Abdualal

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)

Lecture Notes K.Yellaswamy Assistant Professor K L University

Building Strings and Exploring String Class:

More on Strings. String methods and equality. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Compu<ng and Mathema<cs h=p://

CISC 370: Introduction to Java

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

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

Java By Abstraction - Test-B (Chapters 1-6)

York University Fall 2001 / Test #1 Department of Computer Science

Lesson:9 Working with Array and String

Bellwork Strings 11/25/13

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

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

A variable is a name for a location in memory A variable must be declared

More non-primitive types Lesson 06

We now start exploring some key elements of the Java programming language and ways of performing I/O

Using Java Classes Fall 2018 Margaret Reid-Miller

CS 1301 Ch 8, Part A

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

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

CS 106 Introduction to Computer Science I

Midterm Exam 2 Thursday, November 15th, points (15% of final grade) Instructors: Jim Williams and Marc Renault

Building Java Programs

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Designing data types. Fundamentals of Computer Science I

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Objects Classes Strings Review CSC 123 Fall 2018 Howard Rosenthal

JAVA NOTES DATA STRUCTURES AND ALGORITHMS

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

Chapter 8: Strings and Things

- Thus there is a String class (a large class)

STRINGS AND STRINGBUILDERS. Spring 2019

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

Java Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved.

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

Activity 9: Object-Oriented

JAVA NOTES DATA STRUCTURES AND ALGORITHMS

CSC 222: Object-Oriented Programming. Spring 2017

Chapter 1 Introduction to java

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

JAVA NOTES DATA STRUCTURES

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Assignment 5: MyString COP3330 Fall 2017

COMP 401 Midterm. Tuesday, Oct 18, pm-3:15pm. Instructions

Strings! Today! CSE String Methods!

COMP-202: Foundations of Programming

Activity 9: Object-Oriented

Netbeans tutorial:

TEXT-BASED APPLICATIONS

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

Character Strings COSC Yves Lespérance. Lecture Notes Week 6 Java Strings

Using System.out.println()

Lecture 8: The String Class and Boolean Zen

Class. Chapter 6: Data Abstraction. Example. Class

Introduction to Java (All the Basic Stuff)

Review: Python Transi,on Warning

Values and Variables 1 / 30

Follow this and additional works at: Part of the Programming Languages and Compilers Commons

CSC 222: Object-Oriented Programming. Spring 2013

Java Foundations: Unit 3. Parts of a Java Program

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

OOP-Lecture Java Loop Controls: 1 Lecturer: Hawraa Sh. You can use one of the following three loops: while Loop do...while Loop for Loop

CST242 Strings and Characters Page 1

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Transcription:

1 8 THE STRING CLASS Terry Marris 16 April 2001 8.1 OBJECTIVES By the end of this lesson the student should be able to appreciate the difference between a char and a string understand and use the String class methods 8.2 PRE-REQUISITES The student should know what a char is, should understand what the ASCII collating sequence is, and should be comfortable with using messages, receivers, parameters, arguments and return values. 8.3 PREVIEW We see that a string is just an indexed sequence of characters. We can join two strings together, extract substrings from strings, create new strings and test strings for equality. The standard Java package includes many useful classes. One such class is named String. We summarise the most useful String class methods. 8.4 INTRODUCTION In Chapter Nine we saw that a variable of type char holds just one character at a time. A String object holds any number of characters at a time. So where a char variable can hold the value M, a string value could be Medium. char achar = 'M'; String astring = "Medium";

2 8.5 STRINGS We view a string as a sequence of characters. The sequence is always indexed from zero upwards. H e l l o 0 1 2 3 4 Figure 8.1 A String is an indexed sequence of characters H is in index position zero. e is in index position one. And o is in index position four. Notice the difference between char achar = 'M'; and String astring = "M"; achar holds just one character; it cannot hold more than one character at a time. astring can hold many characters at a time but just happens to hold one character in this case. The quotes themselves are not part of the string; they serve to just mark its ends.

3 8.6 charat(int) The char charat(int index) method returns the character at the given index location. We define astring with value "Catastrophe" String astring = "Catastrophe"; And picture C a t a s t r o p h e 0 1 2 3 4 5 6 7 8 9 10 The statement char achar = astring.charat(0); would leave achar containing 'C', the character at index position zero. If we sent the message charat(10) to astring, the character 'e', the character at index position ten, would be returned. If we sent the message charat(-1) or the message charat(11) to astring, an index out of bounds error would occur because astring has no character at index position -1 or at index position 11.

4 8.7 indexof(string) The int indexof(string s) method returns the index position of the given string, s in this string. this string refers to the receiver, that is, the object receiving the message. So, given String astring = "Catastrophe"; int index = astring.indexof("strop"); this string corresponds to astring. The parameter String s corresponds to the argument "strop". int index = astring.indexof("strop"); corresponds to this string corresponds to parameter String s Figure 8.2 Relation between this object and receiver, parameter and argument astring.indexof("strop") returns four because "strop" begins at index location four in astring. And so four is stored in the int variable index. astring.indexof("c") returns zero. Notice the double quotes around the C. These are necessary because indexof(string) demands a String argument value to satisfy its String parameter. astring.indexof("strap") returns -1 because "strap" is not an unbroken sequence of characters within astring. astring.indexof("x") returns -1 for the same reason. What would astring.indexof("c") return? -1? Why?

5 8.8 length() The length of a string is just the number of characters it contains. Look at String astring = "success"; s u c c e s s 0 1 2 3 4 5 6 The length of astring is seven (just count the number of characters it contains - do not include the quotes). The length of a string is always just one more than its last index value (six in our example). The last index value is always just one less than the length of the string. String astring = "success"; int sizeofastring = astring.length(); leaves sizeofastring with value seven. The int length() method returns an int that represents the number of characters in the string. It has no parameters.

6 8.9 substring(int, int) A substring is just part of a string. It could be the entire string itself. It could be the empty string. Substrings of "together" include "to", "get", "her", "together" and "". The method String substring(int from, int to) returns a new string that is a substring of this string, starting with index from up to (but not including) index to. from must be less than to. from cannot be negative nor can to be larger than the length of this string. String astring = "together"; t o g e t h e r 0 1 2 3 4 5 6 7 String asubstring = astring.substring(2, 5); leaves asubstring with value "get", the characters in astring from index position two up to (but not including) index position five. Notice astring.substring(0, 2) returns "to". astring.substring(5, 7) returns "he". astring.substring(5, 8) returns "her" But astring.substring(5, 9) returns an index out of bounds error because there is no character in index location eight. astring.substring(2, 0) also returns an error because the first argument must be less than the second.

7 8.10 EQUALITY Two strings are equal when they both contain exactly the same characters in exactly the same order and are both exactly the same length. These two strings, "cat" and "cat", are equal. These two strings, "cat" and "cut", are not equal. Neither are these two strings: "cat" and "Cat". Case matters. 'c' 'C' remember. The boolean equals(string s) method returns true if this string has the same sequence of characters that s has. String astring = "cat"; boolean isequal = astring.equals("cat"); leaves isequal with the value true. But String astring = "cat"; boolean isequal = astring.equals("cat"); leaves isequal with the value false. If we wish to regard words to be the same even if one contains capitals, and one does not, we uses the boolean equalsignorecase(string s) method. The method returns true if this string has the same sequence of characters that s has when case is not taken into account. String astring = "cat"; boolean isequal = astring.equalsignorecase("cat"); leaves isequal with the value true.

8 8.11 compareto(string) The int compareto(string s) method returns an int less than zero (e.g. -5) if this string comes before s in the ASCII collating sequence, zero if this string is identical to s and an int greater than zero (e.g. 7) 0 if this string comes after s. For example int result = "bat".compareto("cat"); leaves result with a negative value. We are not too concerned with the actual value, just with the fact that it is less than zero. int result = "cat".compareto("cat"); leaves result with the value zero. int result = "cat".compareto("bat"); leaves result with a positive value.

9 8.12 touppercase() The method String touppercase() returns a new string that is a copy of this string except that all lower case characters are converted to upper case. Any upper case characters in this string are left unchanged. For example String astring = "Cat"; String anuppercasestring = astring.touppercase(); leaves anuppercasestring with the character sequence "CAT". 8.13 replace(char, char) The method String replace(char oldch, char newch) returns a new string that results from replacing all occurrences of oldch with newch in this string. If oldch does not occur in this string, this string is returned unchanged. For example "purple purpoise".replace('p', 't') returns turtle tortoise "tom jones".replace('x', 'Y') returns tom jones

10 8.14 CONCATENATION The concatenation operator, +, does two things: it joins one string onto the end of another it converts whatever follows it to a string, if it can. Look at the Java code fragment shown below. int temperature = 20; System.out.println("Temperature is " + temperature); When executed, you expect Temperature is 20 to be displayed on the monitor. The concatenation operator conveniently converts the temperature (an int) into a string for us.

11 8.15 STRING CLASS TEST PROGRAM We try out a few String class methods in a simple test program. /* TestStrings.java Terry Marris August 2000 */ public class TestStrings { public static void main(string[] s) { String greeting = "Hello sailor!"; System.out.println(greeting); String newgreeting = greeting.substring(0, 6) + "ladies!"; System.out.println(newGreeting); System.out.println("The length of the new greeting is " + newgreeting.length()); } } String hello = "hello"; String HELLO = "HELLO"; System.out.println("hello equals HELLO: " + hello.equals(hello)); System.out.println("hello equals HELLO ignoring case: " + hello.equalsignorecase(hello)); The program run is shown below. Hello sailor! Hello ladies! The length of the new greeting is 13 hello equals HELLO: false hello equals HELLO ignoring case: true Exercise Identify which line of coding is responsible for each line of output.

12 8.16 STRING CLASS DOCUMENTATION Some useful methods for dealing with string objects are shown in the following tables. Constructors String() initialises a newly created String object so that it represents an empty string. String(char[] s) initialises a newly created String object with the given array of characters String(String s) initialises a newly created String that is a copy of the given String, s. Methods char charat(int index) returns the character at the given index if the index is between 0 and length()-1. int compareto(string s) returns an int < 0 if this string comes before s in the ASCII collating sequence, 0 if this string is identical to s and an int > 0 if this string comes after s. int comparetoignorecase(string s) same as compareto(string s) but case is not taken into account. boolean endswith(string suffix) returns true if this string ends with the given suffix, or if s is the empty string, or if s equals this string. boolean equals(string s) returns true if this string has the same sequence of characters that s has. boolean equalsignorecase(string s) returns true if this string has the same sequence of characters that s has, when case is not taken into account. int indexof(string s) returns the position in this string of the first occurrence of the given string s. int length() returns the number of characters in this string. String replace(char oldch, char newch) returns a new string that results from replacing all occurrences of oldch with newch in this string. boolean startswith(string s) returns true if this string starts with the given String, s. String substring(int from, int to) returns a new string that is a substring of this string, starting with index from up to (but not including) index to. from must be less than to. from cannot be negative nor can to be larger than the length of this string. String tolowercase() returns a new string that is a copy of this string except that all upper case characters are converted to lower case. String touppercase() returns a new string that is a copy of this string except that all lower case characters are converted to upper case. String trim() returns a new string that is a copy of this string except that all leading and trailing spaces are removed.

13 8.17 FURTHER READING HORSTMANN & CORNELL Core Java 2 Volume 1 Fundamentals pp 59 The document String.html that may be found at c:\jdk1.2\docs\api\java\lang. You could use your regular WEB browser to view this document. 8.18 EXERCISES 1 Print out and read the document String.html that may be found at c:\jdk1.2\docs\api\java\lang. You could use your regular WEB browser to view and print this document. 2 Try out all the methods listed in the table of 8.16 - String Class Documentation.

14 8.19 REVIEW a sequence of zero to many characters indexed from zero enclosed within double quotes String charat(int i) returns the character at location i indexof(string s) returns the location of s in this string equals(string s) returns true if this string and s are the same equalsignorecase(string s) returns true regardless of case replace(char ch1, char ch2) replaces every ch1 in this string with ch2 substring(int start, int stop) returns the chars from position start up to just before position stop touppercase() returns this string entirely in capital letters tolowercase() returns this string entirely in small letters length() returns the number of characters in this string compareto(string s) returns a negative number if this string < s 0 if this string == s a positive number if this string > s comparetoignorecase(string s) same as compareto() but case is ignored