Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Advertisements

Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
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 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.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
String Class in Java java.lang Class String java.lang.Object java.lang.String java.lang.Object We do not have to import the String class since it comes.
Strings.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
EXAM 1 REVIEW. days until the AP Computer Science test.
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 5/27/20161.
Introduction to Java Java Translation Program Structure
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Java Concepts Chapter 2 - Using Objects Mr. Smith AP Computer Science A.
Chapter 7: Characters, Strings, and the StringBuilder.
Characters and Strings. Characters  New primitive char  char letter; letter = ‘a’; char letter2 = ‘C’;  Because computers can only represent numbers,
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Dialog Boxes.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
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.
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,
InterestRate Create an InterestRate class and InterestRateViewer client class to do the following: A person is purchasing an item with their credit card.
Strings Characters and Sentences 1.Overview 2.Creating Strings 3.Slicing Strings 4.Searching for substrings 1.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Input, Output and Variables GCSE Computer Science – Python.
The Methods and What You Need to Know for the AP Exam
Introduction to Computer Science and Object-Oriented Programming
String and Lists Dr. José M. Reyes Álamo.
Sorts, CompareTo Method and Strings
C++ Memory Management – Homework Exercises
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
2.5 Another Java Application: Adding Integers
Variables, Expressions, and IO
Primitive Types Vs. Reference Types, Strings, Enumerations
String Objects & its Methods
Java Strings Slides provided by the University of Washington Computer Science & Engineering department.
CS 177 Week 3 Recitation Slides
CS 106A, Lecture 9 Problem-Solving with Strings
Chapter 7: Strings and Characters
Object Oriented Programming
CIS16 Application Development and Programming using Visual Basic.net
String and Lists Dr. José M. Reyes Álamo.
Introduction to Computer Science
Primitive Types and Expressions
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Data Types and Maths Programming Guides.
Week 3 - Friday COMP 1600.
String Methods Strings have actions known as method. We will review a few of the methods associated with strings that are a part of the built in Java.
Presentation transcript:

Strings Mr. Smith AP Computer Science A

What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as “Hello, World!” Strings are objects Strings are sent messages Strings do not need to be instantiated Strings can be combined using the concatenation operator (+)

Signatures of Useful String Methods int length()  returns the length of the string String substring(int start, int end)  returns the substring beginning at start and ending at (end – 1) String substring(int start)  returns the substring beginning at start and ending at the end of the string int indexOf(String otherString)  returns the index of the first occurrence of otherString  returns -1 if str is not found boolean equals(String otherString)  Compares string to otherString. Returns true if equal (otherwise false).  Never test for string equality by using == Java Concepts 4.6 (Strings), Appendix C (pg. 643)

length int length() Returns the length of a string This is a count of the number of characters in the string, including spaces A string with a length of 0 is called the empty string Examples: String msg = "Hello, World!", str = ""; int msgLen = msg.length(); int strLen = str.length(); Java Concepts 4.6 (Strings) msgLen contains 13 strLen contains 0

substring String substring(int start, int end) Returns a substring of the string The substring is composed of the characters beginning at position start and ending at position (end – 1). In other words, you tell it the position of the first character you want and the position of the first character you do not want. The first position of the string is always position 0 Examples: String msg = "Hello, World!", str1, str2; String str1 = msg.substring(0, 5); String str2 = msg.substring(7, 12); Java Concepts 4.6 (Strings) str1 contains "Hello" H e l l o, W o r l d ! Position: str2 contains "World"

substring String substring(int start) Returns a substring of the string The substring is composed of the characters beginning at position start and ending at the end of the string Examples: String msg = "Hello, World!", str1, str2; String str1 = msg.substring(12); String str2 = msg.substring(7); Java Concepts 4.6 (Strings) str1 contains "!" H e l l o, W o r l d ! Position: str2 contains "World!"

indexOf int indexOf(String otherString) Returns the position of the first occurrence of otherString in the string Returns -1 if otherString is not found in the string Examples: String msg = "Hello, World!"; int pos1 = msg.indexOf("or"); int pos2 = msg.indexOf("x"); Java Concepts 4.6 (Strings) pos1 contains 8 H e l l o, W o r l d ! Position: pos2 contains -1

equals boolean equals(String otherString) Returns true if the string equals otherString or returns false if they are not equal The comparison is case sensitive. Note: you should use equalsIgnoreCase(String otherString) if you want to ignore case during the comparison. Do not use == to compare strings. This will usually not return the desired result Examples: String originalStr = "North", str1 = "South", str2 = "north"; if (originalStr.equals(str1)) if (originalStr.equals(str2)) if (originalStr.equalsIgnoreCase(str2)) Java Concepts (Comparing Strings) false true

Let’s try out these String methods String myTeam = “Carolina Panthers”; String myTeamLower = “carolina panthers”; String answer; int stringLength, stringPos, stringCompare; Write the Java code to answer the following questions: 1. What is the length of myTeam ? stringLength = myTeam.length(); 2. What is the position of the first occurrence of "n" in myTeam ? stringPos = myTeam.indexOf("n"); 3. What are the first 3 characters of myTeam ? answer = myTeam.substring(0, 3); 4. If myTeam equals myTeamLower, print “They are equal”. if ( myTeam.equals(myTeamLower) ) System.out.println(“They are equal”); Java Concepts 4.6 (Strings), Appendix C (pg. 643) stringLength contains 17 stringPos contains 6 answer contains “Car” false, nothing prints

StringCompare Write a StringCompare and StringCompareViewer class to: Have the user input a string (could be a sentence, phrase, etc.) to the console or into an input dialog window. We will name this originalString. Also, have the user input another string (could be one character, several characters, or a phrase) to the console or into an input dialog window. We will name this string2. Your program should take these strings and print the following to the console:  Print the value of each string  Print the length of each string  Find the first occurrence of string2 in originalString and print out the position in originalString where it is found (i.e. if originalString = “Carolina Panthers” and string2 = “ol”, then you should print 3 ).  Compare originalString to string2 and determine if they are equal. Print out a sentence stating whether they are equal.  Print the first word in originalString. Extra credit (worth 2 points each):  Determine the number of words in originalString and print this number to the console. Note that words are separated by a space. Use a while loop.  Determine the number of occurrences of string2 in originalString and print it to the console (i.e. if originalString = “Carolina Panthers are number one” and string2 = “n”, then you should print 4 ). Use a while loop. Remember to test with a few scenarios to make sure that it works 0123

compareTo int compareTo(String otherString) Compares the original string to otherString to see how they alphabetically compare. The comparison is case sensitive. The “dictionary” ordering used by Java is slightly different than a normal dictionary. Java is case sensitive and sorts in this order (lowest to highest):  Space and special characters come before other characters  Numbers are sorted after the space character  Uppercase characters are sorted next  Lowercase characters are sorted after that When Java compares two strings, corresponding letters are compared until one of the strings ends or a difference is encountered. If one of the strings ends, the longer string is considered the later (greater) one. Java Concepts (Comparing Strings)

compareTo int compareTo(String otherString) - continued If the two strings are equal it returns 0. If the original string is less than otherString, it returns a value less than 0. If the original string is greater than otherString, it returns a value greater than 0. Examples: String originalStr = "car", str1 = "cargo", str2 = “casting"; int stringCompare1 = originalStr.compareTo(str1); int stringCompare2 = str1.compareTo(str2); int stringCompare3 = originalStr.compareTo("Bob"); int stringCompare4 = originalStr.compareTo("1car"); These 5 strings are sorted as follows: 1car, Bob, car, cargo, casting Java Concepts (Comparing Strings) stringCompare1 is < 0 stringCompare2 is < 0 stringCompare3 is > 0 stringCompare4 is > 0

String methods *** Java Concepts Appendix C (pg. 643) *** on AP exam

String methods *** Java Concepts Appendix C (pg. 643)

String methods *** Java Concepts Appendix C (pg. 643)

Advanced Operations on Strings Consider the problem of extracting words from a line of text. To obtain the first word, we could find the first space character in the string (assuming the delimiter between words is the space) or we reach the length of the string. Here is a code segment that uses this strategy: Java Concepts 4.6 (Strings), Appendix C (pg. 643)

Advanced Operations on Strings The problem is solved by using two separate String methods that are designed for these tasks. String original = "Hi there!"; // Search for the position of the first space int endPosition = original.indexOf(" "); // If there is no space, use the whole string if (endPosition == -1) endPosition = original.length(); // Extract the first word String word = original.substring(0, endPosition); // Extract the remaining words of the string String remainingWords = original.substring(endPosition+1); Java Concepts 4.6 (Strings), Appendix C (pg. 643)

Integer.parseInt int Integer.parseInt(String str) Use the static method parseInt of the Integer class to convert a string to an integer This is helpful when prompting a user in an input dialog window for an integer The string must be an integer or the program will throw a NumberFormatException error. Examples: String cash = “20"; int dollarAmt = Integer.parseInt(cash); Java Concepts 4.6 (Strings)

Double.parseDouble double Double.parseDouble(String str) Use the static method parseDouble of the Double class to convert a string to a floating point number This is helpful when prompting a user in an input dialog window for a floating point number The string must be an floating point number or an integer or the program will throw a NumberFormatException error. Examples: String cash = "19.75"; double cashAmt = Double.parseDouble(cash); double dollarAmt = Double.parseDouble("20"); Java Concepts 4.6 (Strings)

Let’s try out these String methods String myTeam = “Carolina Panthers”; String myTeamLower = “carolina panthers”; String interestRateStr = “7.50”, ageStr = “18”; int stringCompare, age; double interestRate; Write the Java code to perform the following: 1. Is myTeam equal, less than or greater than myTeamLower ? stringCompare = myTeam.compareTo(myTeamLower); 2. Convert interestRateStr to a floating point number so that it can be used in a calculation. interestRate = Double.parseDouble(interestRateStr); 3. Convert ageStr to an integer so that it can be used in a calculation. age = Integer.parseInt(ageStr); Java Concepts 4.6 (Strings), Appendix C (pg. 643)

InterestRate Create an InterestRate class and InterestRateViewer client class to do the following: A person is purchasing an item with their credit card. Launch an input dialog window and have the user enter a short description of the item they are purchasing. Remember the JOptionPane.showInputDialog method that we used in an earlier class? Have the user input the amount of the purchase (in whole dollars – i.e. integer) into an input dialog window. Have the user input (into another input dialog window) the monthly interest rate they are paying on this purchase. Note that this may include decimal places (i.e. they would enter 5.75 to represent 5.75%). Your program should take these values and do the following:  Calculate the amount the user will be charged in interest if they don’t pay off this credit card purchase after the first month.  Print the following information to the console: You purchased for dollars. Your monthly interest rate is %. You will be charged in interest after the first month. Test with a few scenarios and print out your code and the results