html5-img
1 / 31

Strings

John Sprinkle AP Computer Science A 2006 - 2007. Strings. This PowerPoint deals mainly with the implementation of various String methods, which are really what you need to know to do the required programs.

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. John Sprinkle AP Computer Science A 2006 - 2007 Strings This PowerPoint deals mainly with the implementation of various String methods, which are really what you need to know to do the required programs. It gives straightforward syntax for creating Strings and using its methods effectively. You can even paste the example code (minus the { }) inside your public static void main(String[] args){ } to run it and see exactly what’s going on. However, a brief explanation of the nuts and bolts behind Strings is included. *Note: If you do chose to run any of the code included, you will need to manually change all “” to “” after pasting the code into BlueJ (or another compiler). Quotation marks from Word and other places are not recognized by the compiler for some reason.

  2. Strings are Objects of the String class. Strings are actually arrays of Characters, but this knowledge isn’t necessary to use Strings effectively. Like with all Objects, when you create a String of a given name (for example myString) the name (myString) is really just a reference to the object created. Unlike primitive data types (char, int, boolean…) String names (ex. myString) do not contain the data to which they refer. Thus, one String object can have a multitude of names. The example at the right will clarify. How Strings Work int myNum 8 int num 15 Primitive data types can be though of as “owning” the data they refer to String str String str2 Objects refer to data rather than owning it per say. This is critical when equating one object to another. “Hi There” “Bye there”

  3. Creating Strings • The String constructor syntax looks like this: String myString = new String(“My message”); • However, it can be shortened to a more convenient form: String myString = “My message”; Object Type Variable Name Data of String in “”

  4. 0 1 2 3 4 5 6 7 What’s this Index thing? • A lot of String methods either require indexes as parameters or return them as integer values • An index refers to a particular position in a String • String positions start at 0 and go to the String’s length – 1 For Example: String myStr = “Hi There”; For the String myStr, the indexes are as follows: Hi There In the String, “H” is in position 0, “i” is in position 1, the space is in position 3 (yes spaces count as position slots), the “T” is in position 4, etc. The last position occupied by a String will always be its length – 1 (assuming the String has a length > 0). The first position occupied will always be 0.

  5. indexOf() – returns the index of the first occurrence of the String being searched for lastIndexOf() – returns the index of the last occurrence of the String being searched for compareTo() – compares one String to another, including case compareToIgnoreCase() – compares one String to another, ignoring case toUpperCase() – replaces current String letters with all uppercase letters toLowerCase() – replaces current String letters will all lowercase letters trim() – removes all white space before and after a String substring() – returns a portion of the whole String equals() – returns a boolean value indicating whether two Strings contain the same data (including case) equalsIgnoreCase() – returns a boolean value indicating whether two Strings contain the same data (ignoring case) charAt() – returns the character at a given index length() – returns the integer length of the String replace() – replaces all given instances of a String within the String with a newly specified String (a little confusing, I know) toCharArray() – returns a Character Array of the current String String Methods Overview Listed below are all the prevalent String methods and a brief statement on what they do. Example code is listed on the slides to demonstrate the syntax and actual application of each method.

  6. indexOf() returns the index of the first occurrence of the String passed to the method as a parameter In English, it’s a search You pass what you are looking for in “” within the method like so: indexOf(“”) Example Code: { String myStr = “XxabxabcxxabcxX”; int first = myStr.indexOf(“abc”); System.out.println(first); } This code snippet would print out the number 5 because the first index that “abc” occurs at is 5. The indexOf() method returns the beginning index within the overall String where it first finds the little String being searched for. If the String that you are searching for does not appear in the bigger String, -1 is returned. For instance, if we had searched for “my dog” instead of “abc”, -1 would have been printed to the screen. indexOf() Index of 5

  7. lastIndexOf() returns the index of the last occurrence of the String passed to the method as a parameter In English, it’s a search just like indexOf() except you find the last time something occurs instead of the first You pass what you are looking for in “” within the method like so: lastIndexOf(“”) Example Code: { String myStr = “XxxabcabcabcxxX”; int first = myStr.lastIndexOf(“abc”); System.out.println(first); } This code snippet would print out the number 9 because the last index that “abc” occurs at is 9. The lastIndexOf() method returns the beginning index within the overall String where it last finds the little String being searched for. If the String that you are searching for does not appear in the bigger String, -1 is returned. For instance, if we had searched for “my dog” instead of “abc”, -1 would have been printed to the screen. lastIndexOf() Index of 9

  8. Explanation Click for verbal explanation of how you might use indexOf() / lastIndexOf() Turn on your sound

  9. Ok, compareTo() basically tells how many positions on the ASCII table the first different character of the String that invokes the compareTo() method is past the first different character in the String passed as a parameter is. Yes, that makes absolutely no sense- I know. Take a look at the example. The run down: -If the String calling the method occurs on the ASCII table after the parameter String, a positive number is returned. -Otherwise, a negative number is returned -However, if the Strings are identical, 0 is returned. Example Code: { String str = "This is a dog"; String str2 = "This is A zeebra"; int myNum = str.compareTo(str2); System.out.println(myNum); } str invokes the method. str2 is the String passed as the parameter. The method looks through both Strings one index at a time to find the first different character like so: “This is a dog”; “This is A zeebra”; On the ASCII table, the character ‘a’ is 32 positions past the character ‘A’. Thus, 32 is printed to the screen. Had the code said int myNum = str2.compareTo(str); -32 would have been printed to the screen because ‘A’ is 32 positions behind ‘a’ (or -32 positions in front of it) on the ASCII table. Different character! compareTo()

  10. This method functions exactly the same as compareTo() except that case is ignored. So, if the previous example is reconsidered Example Code: { String str = "This is a dog"; String str2 = "This is A zeebra"; int myNum = str.compareToIgnoreCase(str2); System.out.println(myNum); } str invokes the method. str2 is the String passed as the parameter. The method looks through both Strings one index at a time to find the first different character disregarding case like so: “This is a dog”; “This is A zeebra”; On the ASCII table, the character ‘z’ is 22 positions past the character ‘d’. Thus, 22 is printed to the screen. Had the code said int myNum = str2.compareToIgnoreCase(str); -22 would have been printed to the screen because ‘d’ is 22 positions behind ‘z’ (or -22 positions in front of it) on the ASCII table. Different character! compareToIgnoreCase()

  11. Explanation Click for verbal explanation of how you might use compareTo() / compareToIgnoreCase()

  12. This method simply changes the String that invokes it to all upper case letters. This method has no parameters. Notice numbers and other symbols are not affected Example Code: { String myStr = “hello 123 go”; myStr = myStr.toUpperCase(); System.out.println(myStr); } You can’t simply say: myStr.toUpperCase(); You have to reassign the new data to the name myStr, since in effect you are creating an entirely new object. HELLO 123 GO is output to the screen toUpperCase()

  13. This method does exactly the opposite of toUpperCase() It changes all the letters in a String to lowercase Once again, numbers and symbols are not affected Example Code: { String myStr = “HELLO 123 GO”; myStr = myStr.toLowerCase(); System.out.println(myStr); } You can’t simply say: myStr.toLowerCase(); You have to reassign the new data to the name myStr, since in effect you are creating an entirely new object. hello 123 go is output to the screen toLowerCase()

  14. Explanation Click for verbal explanation of how you might use toUpperCase() / toLowerCase()

  15. This is a great method for when you are reading in file data and cruel instructors throw in white spaces for a laugh In effect, it simply “trims” away any white space at the beginning and end of a String Example Code: { String myStr = “ white space “; System.out.println(“this” + myStr + “my”); myStr = myStr.trim(); System.out.println(“this” + myStr + “my”); } This is output to the screen: this white space my thiswhite spacemy Once again, notice how myStr had to be reassigned the value of myStr.trim(), since in effect a new object has been created. Also notice how the white space between “white space” was not affected. trim() only removes white space at the beginning and end of a String. trim()

  16. Explanation Click for verbal explanation of how you might use trim()

  17. substring() is one of the most useful methods associated with Strings This method functions two ways: -If one index is passed as a parameter, the portion of the String from that index (including the character at that index) to the end of the String is returned -If two indexes are passed as parameters, the portion of the String including the first index up to but not including the final index is returned. (Think of this one as the first character you want to the first character you don’t want) Example Code: (One index) { String myStr = “123456789”; String newStr = myStr.substring(4); System.out.println(newStr); } “123456789”; 56789 is printed to the screen (from and including index four, which is occupied by the character 5 to the end of the String). substring() Index 4 Onward

  18. When two indexes are used as parameters, the numbers are passed in the method separated by a comma like so: substring(#, #) Remember, when using substring() in this way, the indexes provided represent the first character you want to the first character you don’t want. Example Code: (Two indexes) { String myStr = “123456789”; String newStr = myStr.substring(4, 7); System.out.println(newStr); } “123456789”; 567 is printed to the screen (from and including index four, which is occupied by the character 5 to the character immediately before index seven, which is occupied by the character 7). substring() (continued) Index four to Index directly before position seven Index four (included) Index seven (not included)

  19. Explanation Click for verbal explanation of how you might use substring()

  20. This method tests whether the data of two strings is equal (including case). This method is very different from the == test. With primitive types, == tests whether two primitive variables have the same data. With objects (including Strings) == tests whether two Strings refer to the same object. Example Code: { String str = “hello”; String str2 = “hello”; String str3 = “Hello”; String str4 = str2; System.out.println(str.equals(str2)); System.out.println(str.equals(str3)); System.out.println(str == str2); System.out.println(str2 == str4); } This is output to the screen: true false true true You might have expected the third value to be false instead of true right? After all, str and str2 refer to different objects right? Not exactly. String objects are unique in that Java (in order to save memory) won’t create duplicate objects containing the same String data. So, until either str or str2 is altered in some way, they will refer to the same object. However, if str were in some way altered, str2 would be unaffected and have its own “hello” data. equals()

  21. This method functions exactly the same as equals() but ignores case when comparing one String to another. Example Code: { String str = “hello”; String str2 = “Hello”; System.out.println(str.equalsIgnoreCase(str2)); } In this case, true is printed to the screen because the two Strings have identical data if letter case is ignored. equalsIgnoreCase()

  22. Explanation Click for verbal explanation of how you might use equals() and equalsIgnoreCase()

  23. This method will return the character at a given index The character is retrieved using the following syntax: charAt(#) Example Code: { String str = “hello”; System.out.println(str.charAt(1)); } In this case, the letter ‘e’ is printed to the screen because it is the character at index 1. charAt()

  24. Explanation Click once for verbal explanation of how you might use charAt()

  25. This method returns the integer length of the String that invokes the method It is called without any parameters like so: length() Example Code: { String str = “hello”; int length = str.length(); System.out.println(length); } In this case, 5 is printed to the screen because “hello” is 5 characters long. length()

  26. Explanation Click once for verbal explanation of how you might use length()

  27. This method will find all occurrences of a specified String within a larger String and replace those instances with a newly specified String value The syntax is as follows: replace(“oldData”, “newData”) Example Code: { String str = “XxxabcxxxabcxabcXX”; str = str.replace(“abc”, “OOO”); System.out.println(str); } XxxOOOxxxOOOxOOOXX is printed to the screen because all instances of “abc” were replaced with “OOO”. replace() What you want replaced What you want to replace it with

  28. Explanation Click once for verbal explanation of how you might use replace()

  29. At this point, you may or may not have covered arrays. If not, don’t worry about this method too much. The method returns an array of base type char where each index in the array represents a letter of the String. Example Code: { String str = "abc"; char[] myAr = str.toCharArray(); System.out.println(myAr[1]); } b is printed to the screen because it is at position 1 in the array myAr. Basically, the String got split up into an array, character by character. “abc” {a, b, c} toCharArray()

  30. Pertaining to Strings • You can change any primitive data type to a String value by concatenating (adding together)the primitive type with an empty String, represented by empty quotation marks. For instance: int num = 765; String str = num + “”; The String str now contains the data “765”. This can be terribly useful. • Often you may find it necessary to change a String number into a real number of type int that you can work with in calculations. Trying to add “765” to 10 doesn’t produce 775 because Strings just don’t work that way. However, you can change any String number (provided it is pure and contains no letters or symbols) into an int with the Integer.parseInt() call. It works like this: String str = “765”; int num = Integer.parseInt(str); The integer num now contains the int value 765, which can be manipulated by any valid mathematical operation. While you could have accomplished this using int casting and an ASCII table, the parseInt() call saves so much time. You simply put a String variable or some String data into the () and out comes an integer representation.

  31. That’s it!

More Related