2/9/20212.7. String Methods — AP CSAwesome1/13(../_images/time902.png)2.7. String MethodsA string holds characters in a sequence. Each character is at a position orindexwhich starts with 0 asshown below. Anindexis a number associated with a position in a string. The length of a string is thenumber of characters in it including any spaces or special characters. The string below has a length of 14.(../_images/stringIndicies.png)Figure 1: A string with the position (index) shown above each characterNoteThe first character in a string is at index 0 and the last characters is atlength-1.For the AP CS A exam, you only need to know how to use the following String methods. All of the Stringmethod descriptions are included in theAP CS A Java Quick Reference Sheet(-computer-science-a) that you get during the exam so you don’t have to memorize these.int length()method returns the number of characters in the string,including spaces and special characters like punctuation.String substring(int from, int to)method returns a new string with thecharacters in the current string starting with the character at thefromindex and ending at the characterbeforethetoindex (if thetoindex isspecified, and if not specified it will contain the rest of the string).int indexOf(String str)method searches for the stringstrin the currentstring and returns the index of the beginning ofstrin the current string or-1 if it isn’t found.int compareTo(String other)returns a negative value if the current stringis less than theotherstring alphabetically, 0 if they have the samecharacters in the same order, and a positive value if the current string isgreater than theotherstring alphabetically.boolean equals(String other)returns true when the characters in thecurrent string are the same as the ones in theotherstring. This method isinherited from the Object class, but isoverridenwhich means that theString class has its own version of that method. A string holds characters in a sequence. Each character is at a position or index which starts with 0 as shown below. An index is a number associated with a position in a string. The length of a string is the number of characters in it including any spaces or special characters. The string below has a length of 14.
Note The first character in a string is at index 0 and the last characters is at length - 1. The String class which is built into the default java.lang library simplifies a lot of complex programming tasks for us. Classes are grouped together into a package like java.lang. Many other useful library packages can be imported in. Programmers provide Application Program Interfaces (APIs) to allow other programmers to use their code. Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class. The String class has many useful methods that you can view in the Java String API. This unit explores a few of the methods.
Run the code below to see the output from the String methods length, substring, and indexOf. The length method returns the number of characters in the string, not the last index which is length-1. The str.substring(from,to) method returns the substring from the from index up to (but not including) the to index. The method str.indexOf(substring) returns the index of where it finds substring in str or -1 if it is not there.
This code shows the output from String methods length, substring, and indexOf. How many letters does substring(0,3) return? What does indexOf return when its argument is not found? public class Test1 { public static void main(String[] args) { String message1 = "This is a test"; String message2 = "Hello Class"; System.out.println(message1.length()); System.out.println(message2.length()); System.out.println(message1.substring(0,3)); System.out.println(message2.substring(4,5)); System.out.println(message1.substring(5)); System.out.println(message1.indexOf("is")); // This will match the is in "This"! System.out.println(message1.indexOf("Hello")); System.out.println(message2.indexOf("Hello")); System.out.println(message2.toLowerCase()); System.out.println(message2.toUpperCase()); } } ==== import static org.junit.Assert.*; import org.junit.*;; import java.io.*; public class RunestoneTests extends CodeTestHelper { @Test public void testMain() throws IOException { String output = getMethodOutput("main"); String expect = "14\n11\nThi\no\nis a test\n2\n-1\n0\nhello class\nHELLO CLASS"; boolean passed = getResults(expect, output, "Expected output from main", true); assertTrue(passed); } }
Note Remember that substring(from,to) does not include the character at the to index! To return a single character at index i, use str.substring(index, index + 1).
2-7-2: What is the value of pos after the following code executes? String s1 = "abccba"; int pos = s1.indexOf("b");
2-7-3: What is the value of len after the following code executes? String s1 = "baby"; int len = s1.length();
2-7-4: What is the value of s2 after the following code executes? String s1 = "baby"; String s2 = s1.substring(0,3);
2-7-5: What is the value of len after the following executes? String s1 = "Miss you!"; int len = s1.length();
2-7-6: What is the value of s2 after the following code executes? String s1 = "baby"; String s2 = s1.substring(2); We can compare primitive types like int and double using operators like == and < or >, which you will learn about in the next unit. However, with reference types like String, you must use the methods equals and compareTo, not == or < or >. The method compareTo compares two strings character by character. If they are equal, it returns 0. If the first string is alphabetically ordered before the second string (which is the argument of compareTo), it returns a negative number. And if the first string is alphabetically ordered after the second string, it returns a positive number. (The actual number that it returns does not matter, but it is the distance in the first letter that is different, e.g. A is 7 letters away from H.) ¶ The equals method compares the two strings character by character and returns true or false. Both compareTo and equals are case-sensitive. There are case-insensitive versions of these methods, compareToIgnoreCase and equalsIgnoreCase. Run the example below to see the output from compareTo and equals. Since “Hello!” would be alphabetically ordered after “And”, compareTo returns a positive number. Since “Hello!” would be alphabetically ordered before “Zoo”, compareTo returns a negative number. Notice that equals is case-sensitive.
Run the code to see how the String methods equals and compareTo work. Is equals case-sensitive? When does compareTo return a negative number? public class Test2 { public static void main(String[] args) { String message = "Hello!"; System.out.println(message.compareTo("Hello there")); System.out.println(message.compareTo("Hello!")); System.out.println(message.compareTo("And")); System.out.println(message.compareTo("Zoo")); System.out.println(message.equals("Hello!")); System.out.println(message.equals("hello!")); } } ==== import static org.junit.Assert.*; import org.junit.*;; import java.io.*; public class RunestoneTests extends CodeTestHelper { @Test public void testMain() throws IOException { String output = getMethodOutput("main"); String expect = "1\n0\n7\n-18\ntrue\nfalse"; boolean passed = getResults(expect, output, "Expected output from main", true); assertTrue(passed); } }
Note Strings are immutable which means that they can’t change. Anything that you do to modify a string (like creating a substring or appending strings) returns a new string.
2-7-10: What is the value of s2 after the following code executes? String s1 = new String("hi there"); int pos = s1.indexOf("e"); String s2 = s1.substring(0,pos);
2-7-11: What is the value of s1 after the following code executes? String s1 = "Hi"; String s2 = s1.substring(0,1); String s3 = s2.toLowerCase();
2-7-12: What is the value of s3 after the following code executes? String s1 = "Hi"; String s2 = s1.substring(0,1); String s3 = s2.toLowerCase();
2-7-13: What is the value of answer after the following code executes? String s1 = "Hi"; String s2 = "Bye"; int answer = s1.compareTo(s2); The following code shows some common mistakes with strings.
This code contains some common mistakes with strings. Fix the code to use the string methods correctly. public class StringMistakes { public static void main(String[] args) { String str1 = "Hello!"; // Print out the first letter? System.out.println("The first letter in " + str1 + ":" + str1.substring(1,1) ); // Print out the last character? System.out.println("The last char. in " + str1 + ":" + str1.substring(8) ); // Print str1 in lower case? Will str1 change? str1.toLowerCase(); System.out.println("In lowercase: " + str1); } } ==== import static org.junit.Assert.*; import org.junit.*;; import java.io.*; public class RunestoneTests extends CodeTestHelper { @Test public void testMain() throws IOException { String output = getMethodOutput("main"); String expect = "The first letter in Hello!:H\nThe last char. in Hello!:!\nIn lowercase: hello!"; boolean passed = getResults(expect, output, "Expected output from main"); assertTrue(passed); } }Here is a list of common mistakes made with Strings.
|