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

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

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

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

STUDENT LESSON A10 The String Class

CS112 Lecture: Characters and Strings

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

Using Java Classes Fall 2018 Margaret Reid-Miller

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

More on variables and methods

More non-primitive types Lesson 06

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

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

Creating Strings. String Length

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Programming with Java

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

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

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

Strings! Today! CSE String Methods!

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

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

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

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

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

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

Object-Oriented Programming

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.

Lab 14 & 15: String Handling

Eng. Mohammed Abdualal

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

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

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

String is a Class; Quoted Text is an Object

CS102: Variables and Expressions

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

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

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

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

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

Building Strings and Exploring String Class:

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

Evil Hangman Project

Comments in a Java Program. Java Overview. Identifiers. Identifier Conventions. Primitive Data Types and Declaring Variables

Part III Appendices 165

CS 1301 Ch 8, Part A

Lecture Notes K.Yellaswamy Assistant Professor K L University

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Computing with Numbers

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Section 2: Introduction to Java. Historical note

Variables, Constants, and Data Types

Getting started with Java

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Midterms Save the Dates!

There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:

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

Full file at

CHAPTER 6 MOST COMMONLY USED LIBRARIES

CSC 222: Object-Oriented Programming. Spring 2013

Number Systems Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur Number Representation

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

Mr. Monroe s Guide to Mastering Java Syntax

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

CS 106 Introduction to Computer Science I

CSC 222: Object-Oriented Programming. Spring 2017

Basic data types. Building blocks of computation

Classes and Objects Part 1

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

Program Fundamentals

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

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

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

Pace University. Fundamental Concepts of CS121 1

Unit 4: Classes and Objects Notes

Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F

Lecture Notes for CS 150 Fall 2009; Version 0.5

AP Computer Science A

Designing data types. Fundamentals of Computer Science I

Lecture 4. Strings, Wrappers, & Containers

CS 106A, Lecture 9 Problem-Solving with Strings

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

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

Standard 11. Lesson 9. Introduction to C++( Up to Operators) 2. List any two benefits of learning C++?(Any two points)

Lesson:9 Working with Array and String

Java Foundations: Unit 3. Parts of a Java Program

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

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

Chapter 10: Text Processing and More about Wrapper Classes

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

CMPSCI 187 / Spring 2015 Hangman

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

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

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

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

Computer Science 145 Midterm 1 Fall 2016

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

Java characters Lecture 8

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

Transcription:

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring 2016 Topic Notes: Strings This semester we ve spent most of our time on applications that are graphical in nature: Manipulating graphical objects Implementing animation Many practical programs, however, are not graphical in nature. Many are textual, and require some of the mechanisms for text processing. Much of what is in these notes is review of things you have seen earlier this semester or in previous coursework. Please read through these notes and don t hesitate to ask questions if anything is unclear. Java sstring class Where have we seen examples of the JavaString class? We can define variables and parameters of type String. You can assign values to String names, and you can write methods that return Strings as results. Recall from the drag students example that we declared an array of Strings representing file names of your images. We can specify String constants in programs by placing double quotes around a sequence of characters: msg.settext("got me!"); We can concatenate (glue together) Strings; or we can glue together a String and a numeric value to make a newstring: mousecount.settext("you clicked " + count + " times."); We can determine if two Strings look the same by using the equals method. We saw this, for example, when looking up which entry is currently selected in ajcombobox. It is important to remember to useequals to check for equality, rather than== or you will not get your expected result. == checks if we are looking at the exact same String (in the computer s memory) rather than two String objects which happen to have the same contents. Recall that we saw this same idea when comparinglocation objects.

Uniqueness of Java sstrings Most Java types we ve seen fall neatly into one of two categories: Object types (e.g.,filledrect,text,scanner) Described by a class definition Created using constructor andnew command Manipulated through invocation of methods Can be placed into anarraylist Non-object (i.e., base, or primitive) types (e.g.,int,boolean,double) Members of each of these types are described by constants such as 3, true, 49.7 Manipulated through operator symbols like +, &&, * Can be placed in arrays, but must be wrapped in capital letter classes to be placed in anarraylist Java considers String to be an object type. But Strings share features with both object and non-object types. Can be described by constants ("hello"), like base types Can be manipulated using an operator symbol (+), like base types Can be created using a constructor andnew command like objects Can be manipulated by invoking methods, like objects. In fact, there are over 50 methods in thestring class! Some usefulstring methods public int length() returns the length of a string. String coursename = "Data Structures"; int namelength = coursename.length(); namelength gets the value 15. 2

public int indexof(string s) returns the starting index of the first occurrence of strings; returns-1 ifswas not found. coursename.indexof("s") returns the value 5. Note that indexing starts at 0, as it does with arrays. Of course, we can also say and then String searchstring = "S"; coursename.indexof(searchstring) Another option is: public int indexof(string s, int startindex) which begins its search at the specified index. What are the results of each of the following? coursename.indexof("struct", 2) coursename.indexof("struct", 8) coursename.indexof("t", 2) coursename.indexof("t", 6) coursename.indexof("t", 7) Answers: 5, -1, 2, 6, 10. Here is a method that searches for the number of occurrences of astring,word, in another String,text. public int wordcount(string text, String word) { int count = 0; int pos = text.indexof(word,0); while (pos >= 0) { count++; pos = text.indexof(word,pos+word.length()); return count; What does the above method return for these call? 3

wordcount("yabbadabbadoo","abba"); wordcount("scoobydoobydoo","oo"); How about this one? [Side note: I bet everyone knows where the strings above come from but what about this next one?] wordcount("bubbabobobbrain","bob"); Is that what you want? How would you modify the method to include the overlapped bob s above? Converting strings Note that"s" and"s" are different strings. public String tolowercase() public String touppercase() A case-insensitive word counter/finder differs from the above code only by the added two lines in the following. private int substringcounter( String text, String word) { int count = 0; int pos; text = text.tolowercase(); word = word.tolowercase(); pos = text.indexof(word,0); while ( pos >= 0 ) { count++; pos = text.indexof(word,pos+word.length()); return count; Note that the assignment statements to text and word are required. String methods do not manipulate the givenstring. They make a brand new one. We say that JavaStrings are immutable. Cutting and pasting strings 4

To paste together two strings, use + To cut (i.e., to extract a substring of a string) use: public String substring(int startindex, int indexbeyond) For example: String counttext = "3 Balls, 2 Strikes, 2 Outs"; String strikesonly; strikesonly = counttext.substring(9,18); Note that if we omit the second parameter, the substring returned is the one starting at startindex and will include the rest of the string. Continuing the example above: Link finder: String outsonly; outsonly = counttext.substring(20); We want to write a program to find and extract all of the links in an HTML file. To do this, we need to know how a link is defined in an HTML file: <a href="the URL">link </a> So we need to find the tags <a> and </a> that surround the URL. Convert the string that is the HTML file to lowercase. String links = ""; Find the first position of <a While there is a link remaining (i.e.,tagpos is not 1) Find the other end of it - i.e., > Get the substring between those (that s the URL) Concatenate it to links found so far Find the next <a // Extract all the links from a web page private String findlinks(string fullpage) { int tagpos, tagend; // Start of <A tag specification // Position of first ">" after tag start // A lower case only version of the page for searching String lowerpage = fullpage.tolowercase(); 5

// Text of one A tag String tag; // The A tags found so far String links = ""; // Paste stuff on end of page to ensure searches succeed fullpage = fullpage + " >"; tagpos = lowerpage.indexof("<a ",0); while (tagpos >= 0 ) { tagend = fullpage.indexof(">",tagpos+1); tag = fullpage.substring(tagpos, tagend+1); links = links + tag + "\n"; tagpos = lowerpage.indexof("<a ", tagend); return links; Miscellaneous interestingstring methods public boolean startswith(string s) // true only if this string starts with s public boolean endswith(string s) // true only if this string ends with s public boolean equals(string s) // true only if this string has same sequence of chars as s public boolean equalsignorecase(string s) // true only if this string has same sequence of chars as s // except capital & lower case letters considered the same public int lastindexof(string s) public int lastindexof(string s, int startindex) // return index of last occurrence of s (occurring at or 6

// before startindex) in this string, and -1 if no match. public String replace(char oldchar, char newchar) // Returns a new string resulting from replacing all // occurrences of oldchar in this string with newchar. public String trim() // Returns a new string with leading and trailing spaces removed. public int compareto(string s) // Returns negative int if string before s in case-sensitive // dictionary order; // returns 0 if equal // returns positive int if string after s in case-sensitive // dictionary order. public char charat(int index) // Returns the character at the specified index. Characters OurStrings are made up of characters, so let s take a look at that idea. In some sense, a Java String is really an array of characters, but we don t treat it like a regular array. In C, strings are actually nothing more than an array of characters. A character is what you probably expect roughly speaking, it is a keyboard character. This includes special function characters (like newline and tab), in addition to alphanumeric and punctuation characters. A character is represented internally as a number an integer, in fact. There are various universal codes that can be used to represent characters: ASCII (256 chars) (American Standard Code for Information Interchange) EBCDIC (Extended Binary Coded Decimal Interchange Code) Unicode Allows up to 65,536 chars. About 35,000 currently in use. First 256 are the same as ASCII codes (for compatibility). To declare a variable to be of character type: private char letter; 7

Use single quotes for character constants: H is achar;"h" is astring: char letter = H ; Hangman Let s look at the use of somestring methods to play a simple game of Hangman. See Example: Hangman This word/letter guessing game uses Java s Strings but also reviews how we can read input from the keyboard in the terminal window and how to read input from a data file. The first part of the program we want to look at is the construction and initialization of our list of words. These words are located in a file dictionary.txt, which contains about 127,000 words. We will put these into anarraylist ofstrings. The implementation makes use of Java s Scanner class, which allows us to read the contents of the file word by word, and add them to the word list. The program then prepares to play the game. We create a Java standard random number generator (arandom object). Then we create anotherscanner that allows us to read things typed in the terminal window. The main loop involved picking a random word from the dictionary and presenting the player with a number of blanks equal to the number of letters in the word. The player is prompted for guesses (letters). Along the way, we keep track of which letters have been guessed and how many incorrect guesses have been made. If the player runs out of guesses, we have a hangman and the player loses. If the player has guessed all of the letters, the player wins. Otherwise, the word is displayed again, now with any guessed letters shown. 8