1 / 21

Strings

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

feoras
Download Presentation

Strings

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 UsefulString 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(); msgLen contains 13 strLen contains 0 Java Concepts 4.6 (Strings)

  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); H e l l o , W o r l d ! Position: 0 1 2 3 4 5 6 7 8 9 10 11 12 str1 contains "Hello" str2 contains "World" Java Concepts 4.6 (Strings)

  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); H e l l o , W o r l d ! Position: 0 1 2 3 4 5 6 7 8 9 10 11 12 str1 contains "!" str2 contains "World!" Java Concepts 4.6 (Strings)

  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"); H e l l o , W o r l d ! Position: 0 1 2 3 4 5 6 7 8 9 10 11 12 pos1 contains 8 pos2 contains -1 Java Concepts 4.6 (Strings)

  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)) false false true Java Concepts 5.2.3 (Comparing Strings)

  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: • What is the length of myTeam ? stringLength = myTeam.length(); • What is the position of the first occurrence of "n" in myTeam ? stringPos = myTeam.indexOf("n"); • What are the first 3 characters of myTeam ? answer = myTeam.substring(0, 3); • If myTeam equals myTeamLower, print “They are equal”. if ( myTeam.equals(myTeamLower) ) System.out.println(“They are equal”); stringLength contains 17 stringPos contains 6 answer contains “Car” false, nothing prints Java Concepts 4.6 (Strings), Appendix C (pg. 643)

  10. StringCompare Write a StringCompare and StringCompareViewer class to: • Have the user input a sentence to the console or into an input dialog window. • Also, have the user input a search value (could be one character, several characters, or a phrase) to the console or into an input dialog window. We will name this searchValue. • Your program print the following to the console: • Print the strings contained in the sentence and the searchValue strings • Print the length of both the sentence and the searchValue strings • Find the first occurrence of searchValue in the sentence and print out the position in sentence where it is found (i.e. if sentence contains “Carolina Panthers” and searchValue contains “ol”, then you should print 3 ). • Compare sentence to searchValue and determine if they are equal. Print out a sentence stating whether they are equal or not. • Print the first word in the sentence string. • Extra credit (worth 2 points each): • Determine the number of words in sentence 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 searchValue in sentence and print it to the console (i.e. if sentence contains “Carolina Panthers are number one” and searchValue contains “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): S N U L (lowest 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(“Don"); int stringCompare4 = originalStr.compareTo("1car"); If these 5 strings are sorted: 1car, Don, car, cargo, casting stringCompare1 is < 0 stringCompare2 is < 0 stringCompare3 is > 0 stringCompare4 is > 0 Java Concepts 5.2.3 (Comparing Strings)

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

  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: • Is myTeam equal, less than or greater than myTeamLower ? stringCompare = myTeam.compareTo(myTeamLower); • Convert interestRateStr to a floating point number so that it can be used in a calculation. interestRate = Double.parseDouble(interestRateStr); • 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 <description of item> for <amount of purchase> dollars. Your monthly interest rate is <monthly interest rate> %. You will be charged <interest amount> in interest after the first month. • Test with a few scenarios and print out your code and the results

More Related