Download presentation
Presentation is loading. Please wait.
Published byVeronica Shaw Modified over 9 years ago
1
Strings Mr. Smith AP Computer Science A
2
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 (+)
3
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)
4
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
5
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: 0 1 2 3 4 5 6 7 8 9 10 11 12 str2 contains "World"
6
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: 0 1 2 3 4 5 6 7 8 9 10 11 12 str2 contains "World!"
7
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: 0 1 2 3 4 5 6 7 8 9 10 11 12 pos2 contains -1
8
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 5.2.3 (Comparing Strings) false true
9
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
10
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
11
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 5.2.3 (Comparing Strings)
12
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 5.2.3 (Comparing Strings) stringCompare1 is < 0 stringCompare2 is < 0 stringCompare3 is > 0 stringCompare4 is > 0
13
String methods *** Java Concepts Appendix C (pg. 643) *** on AP exam
14
String methods *** Java Concepts Appendix C (pg. 643)
15
String methods *** Java Concepts Appendix C (pg. 643)
16
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)
17
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)
18
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)
19
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)
20
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)
21
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.