Searching and Strings IST 256 Application Programming for Information Systems.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Strings in Java 1. strings in java are handled by two classes String &
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Java Programming Strings Chapter 7.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
Java Strings in 10 minutes
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
CIS 234: Strings. What Is a String? series of characters enclosed in double quotes characters can include letters (lower case and upper case), digits,
Programming with Collections Collections in Java Using Arrays Week 9.
Using the Java API
Quicksort.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Introduction to Methods. How do we use Methods in Java? Let us start by creating one which displays “hello” on Dos Prompt.
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Question Hot Seat public MyConstructor (int a, int b) { index = a+b; } A.Parameters B.Class Name C.Body D.Modifier Please put match these choices to these.
CIS 234: Strings (click, scroll down)Strings Dr. Ralph D. Westfall April, 2010.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Arrays Tonga Institute of Higher Education. Introduction An array is a data structure Definitions  Cell/Element – A box in which you can enter a piece.
Chapter 8: Arrays.
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
P p Chapter 11 discusses several ways of storing information in an array, and later searching for the information. p p Hash tables are a common approach.
Introduction to Java Java Translation Program Structure
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 8 SEARCHING CSEB324 DATA STRUCTURES & ALGORITHM.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
CSCI 51 Introduction to Programming March 12, 2009.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
Arrays, Methods, Error Handling. Using Arrays as Parameters int[] anArray = ; int index = min(anArray); // Index of smallest int index = search(anArray,
CSC Programming I Lecture 9 September 11, 2002.
Composition When one class contains an instance variable whose type is another class, this is called composition. Instead of inheritance, which is based.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming strings.
Strings in Java. What data types have we seen so far?
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Strings Methods in the String class Manipulating text in Java.
Dynamic Programming & Memoization. When to use? Problem has a recursive formulation Solutions are “ordered” –Earlier vs. later recursions.
Strings and I/O. Lotsa String Stuff… There are close to 50 methods defined in the String class. We will introduce several of them here: charAt, substring,
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Vector program patterns Vectors contain many elements, so loops are common. Counted processing // Print the first 3 elements. for (int i = 0; i < 3; i++)
CSCI 51 Introduction to Programming March 10, 2009.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
Common Elementary Algorithms Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: a)Some programming.
Java String Methods - Codehs
CSC 222: Object-Oriented Programming
String class.
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
Searching CSCE 121 J. Michael Moore.
MSIS 655 Advanced Business Applications Programming
Tonga Institute of Higher Education
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
The compareTo interface
Microsoft Visual Basic 2005: Reloaded Second Edition
CS2011 Introduction to Programming I Strings
String Processing 1 MIS 3406 Department of MIS Fox School of Business
Introduction to Computer Science
Strings in Java.
Problem 1 Given n, calculate 2n
Strings in Java Strings in Java are also a reference type.
Methods in the String class Manipulating text in Java
Unit-2 Objects and Classes
Presentation transcript:

Searching and Strings IST 256 Application Programming for Information Systems

Searching for Strings In an array, we do a simple linear search for an item by going through the array in order from the first and comparing each item to the search string. 2 String [ ] names = new String [20]; String searchname = … ; // get a value to search for for (int i = 0; i < names.length; i ++) { if ( names[i].equals(searchname)) { //found one! }

Searching for Strings If we want to find only one (the first one), we can save it and exit from the loop: 3 String [ ] names = new String [20]; String searchname = … ; // get a value to search for String resultname = “”; for (int i = 0; i < names.length; i ++) { if ( names[i].equals(searchname)) { resultname = names[i]; break; } // display the result “break” causes the program to break out of the loop; immediately jump to the end

Searching for Strings But if we don’t find one, we can display that, too: 4 String [ ] names = new String [20]; String searchname = … ; // get a value to search for String resultname = “”; for (int i = 0; i < names.length; i ++) { if ( names[i].equals(searchname)) { resultname = names[i]; break; } // if still empty result, then it was not found if (resultname.equals(“”) { resultname = “No match found.” } // display resultname

Searching for Strings If there’s more than one match, we can find them all: 5 String [ ] names = new String [20]; String searchname = … ; // get a value to search for String resultheader = “ Result: :”; String resultnames = “”; for (int i = 0; i < names.length; i ++) { if ( names[i].equals(searchname)) { resultnames = resultnames + “ ” + names[i]; } // if still empty result, then none was found if (resultnames.equals(“”) { resultnames = “No match found.” } // display resultheader + resultnames

Search Criteria So far, we have used an exact string match with the string function equals names[i].equals(searchname) Suppose that we want to find names where the search name is the start of the name (e.g. “Alex Brown” and we search for “Al” or “Alex”) names[i].startsWith(searchname) uses the String function startsWith 6

Search Criteria Or suppose that we want the strings to match regardless of capitalization. This is called “ignoring case”, and we can achieve this by converting both strings to all lower case, and then comparing them names[i].toLowerCase.equals(searchname.toLowerCase) 7

Search Criteria Or suppose that we want to find the search string as a substring of the name, anywhere that it occurs. There is a String function indexOf that finds a substring and returns an integer that is the number of the character where the substring occurs (starting from 0) if searchname is “Alex”, searchname.indexOf(“ex”) returns the integer 2, the position where “ex” is in “Alex” But if the substring is not found, indexOf returns -1, so our search criteria becomes names[i].indexOf(searchname) != -1 8

Other String Functions Other useful functions include: –endsWith –lastIndexOf –toUpperCase A complete list is found in the API under the String class: – which now redirects to –Where you scroll down to find the String class in the lower left pane 9

Search that returns index In the examples so far, when we found a string that matches, we display or save the string. But sometimes we should just save the index where we found the match –This is particularly useful in an array of class instances, where we search on one criteria (height of student) but want to display another (name of tallest student) 10 String [ ] names = new String [20]; String searchname = … ; // get a value to search for String resultindex = -1; for (int i = 0; i < names.length; i ++) { if ( names[i].equals(searchname)) { resultindex = i; break; } // display the result at resultindex, // where resultindex == -1 means “not found”

Searching for largest or smallest In this case, we are not searching to match an already known value, but searching to find the one larger or smaller than all the rest Strategy: –Pick the first one to be the “largest so far”, –Loop over the array: if any item is larger, make it be the “largest so far” –At the end of the loop, the “largest so far” is largest 11

Example: Hottest Temperature In this example, we assume an array of (integer) temperatures and we find the largest value: 12 int indexSoFar, hottestTemp; // index of hottest temperature so far is at 0 indexSoFar = 0; // loop over array to keep finding index of new hottest temperature so far for(int i = 1; i < numtemps; i++) { if (temperatures[i] > temperatures[indexSoFar]) { indexSoFar = i; } hottestTemp = temperatures[indexSoFar]; hottestLabel.setText("Hottest temperature: " + hottestTemp);

Digression on primitive types vs. classes In Java, primitive types (int, double, boolean) use operators, while classes have fields and methods. But arrays and Strings have a mix: 13 OperatorsUse new constructorUse fields and methods Primitive types: int, double, boolean Yes +, -, *, /, &&, || No ArraysIndexing: [ ]Mostly: new int [ ].length StringsCatenation: +NoMostly:.equals, indexOf, etc. Everything elseNoYes