Is there a method in the string class that returns the number of characters in the string?
Although concatenation is the only operator that can be applied to String objects, Java has many methods in the String class that allow us to manipulate text quite easily. In Chapter 3, we examined the methods equals and compareTo that can be used for comparing and ordering strings. In this section, we extend our study of string methods with an examination of many of the more commonly used ones. Our study will not be complete; if you are going to be doing a lot of work with strings, it would probably be a good idea to take a close look at the full set of methods available in the class. Show
In some ways, strings in Java are much like arrays. For example, both arrays and strings have lengths associated with them. The concepts are not, however, identical. For an array, its length is a property; the array a has a length given by a.length. On the other hand, the length of a string is given by the instance method Length in the String class that returns the number of characters in its implicit object; the string s has a length given by the value of s.length(). Example 1 If we had made the declaration charAt Another concept seen with both arrays and strings is that of an index. Recall that, for an array, an index gave the position of an element in the array, starting from zero. With strings, an index gives the position of a character in the string, again starting from zero. There are a number of methods in the String class that use an index. The simplest is charAt, an instance method whose header has the form public char charAt (int i)The method returns the value of the character at index i in its implicit String object. A value of i out of the range of the string will cause a StringIndexOutOfBoundsException to be thrown.2 Example 2 Suppose that we have made the declaration
indexOf The method indexOf enables us to locate a particular character in a string. The method is overloaded with the simplest version having the following header: public int indexOf (char c)This method searches its implicit String object from left to right for an occurrence of c. If c is a character in the string, the method returns the index of the leftmost occurrence of c; if c does not occur in the string, the method returns -1. The type of argument passes to indexOf is normally char but the method permits the use of an arguments of any integer type other than long. Another version of indexOf is useful if we do not necessarily want the leftmost occurrence of a character. This version has the header public int indexOf (char c, int i)This form of the method returns the index of the first occurrence of c that has index at least equal to i. As before, it returns -1 if no such occurrence exists. Example 3 Given the declaration To illustrate how these methods can be used, the next example shoes two ways that we could perform a simple task involving strings. Example4 Both versions of method printLocations print the indices in the string s of the locations that contain the character c. The first method uses charAt to examine every character while the second method uses indexOf to jump to the locations in which the character occurs. In the second method, the constant NOT_FOUND is set to -1, the value returned be indexOf if it fails to find the specific character. public static void printLocations (char c, String s) { for (int i = 0; i < s.length(); i++) if (s.charAt(i) == c) System.out.println(i); } public static void printLocations (char c, String s) { final int NOT_FOUND = -1; int next = s.indexOf(c); while (next != NOT_FOUND) { System.out.println(next); next = s.indexOf(c,next+1); } }substring Just as we can use charAt to extract characters from a string, we can use substring to extract a part of a string from a string. The substring method, like indexOf, is overloaded. Its simplest form has the header public String substring (int start)this method returns a String object, the substring of its implicit object starting at the index specified by start and continuing the end of the string. If the value of start is less than zero or greater than the length of the string, the method throws a StringIndexOutOfBoundsException. This method also exists in a two-parameter form with the header public String substring (int start, int pastEnd)this form returns a substring of its implicit object from the index specified by start to the character before the index specified by pastEnd. Although this may appear at first to be a bit strange, it turns out to be a useful and convenient form. For one thing, in this form the length of the substring is specifies simply by the difference between the two parameters. Example 5 String s = "Brian Auyeung"; then a) s.substring(3) will return "an Auyeung" b) s.substring(2,5) will return "ian" c) s.substring(20) will throw a StringIndexOutOfBoundsException trim Another method that is useful in manipulating strings containing text is trim, an instance method in the String class that returns a string that is identical to its implicit object but with any leasing or trailing blanks removed. It also removes any leasing or trailing white space characters. White space includes blanks and control characters such as tab (\t), newline (\n), carriage return (\r), and form feed (\f) characters. The method does not alter the original, immutable string. Instead, it creates a copy with the appropriate alterations. Example 6 Given thats = " Lots of extra blanks "; then s.trim() will return the string "Lots of extra blanks" with no leading or trailing white spaces. Notice that the method does not alter interior blanks; the extra blanks between words in s are still in the string returned by the method. To show these methods in context, let us construct a method that removes all excess blanks in a string. Example 7 The following method will create a string identical to its string parameter but with all leading blanks, trailing blanks and instances of two or more consecutive blanks removed. The method first uses trim to eliminate any leading or trailing white space it then uses indexOf to locate remaining blanks. For each blank found by indexOf, charAt is used to see if the adjacent character is also a blank and, if it is, substring is used to eliminate the second blank. Once all excess blanks have been removed, the method returns the compressed string. public static String removeSpaces (String oldString) { final int NOT_FOUND = -1; String newString = oldString.trim(); int nextBalnk = newString.indexOf(' '); while (nextBlank != NOT_FOUND) { while (newString.charAt(nextBlank+1) == ' ') newString = newString.substring(0,nextBlank+1) + newString.substring(nextBlank+2); nextBlank = newString.iindexOf(' ',nextBlank+1); } return newString; }To use this method to eliminate excess blanks in myString, we could write myString = removeSpaces(myString);toUpperCase toLowerCase equalsIgnoreCaseRecall that, in comparing strings, upper case letters and lower case letters are considered to be different. If we want to compare strings containing letters, we can avoid problems involving the case of letters in a number of ways. One possibility is to create a string that is equal to a given string but with all letters converted to upper case (and all other characters left unchanged) by using the method toUpperCase() from the String class. The method has header public String toUpperCase()As you might expect, there is also a method called toLowerCase in the String class whose form and behaviour are exactly analogous to that of toUpperCase. As usual, since strings are immutable, neither of these methods alters its implicit string object. Instead, they return new string objects that may contain new characters. One other solution to the problems produced by different cases is to do comparisons with the method equalsIgnoreCase which has header boolean equalsIgnoreCase (String other)Its effect is exactly the same as that of equals but, as the name suggests, upper and lower case characters will be considered equal. Example 8Given the declarationString s = "Bart & Lisa"; then a) s.toLowerCase() will return "bart & lisa" b) s.toUpperCase() will return "BART & LISA" c) s.equalsIgnoreCase("BART & lisa") will return true valueOfValues of any type can be converted to strings. To convert an object to a string, we can use the object�s toString method. To convert a value in any of Java�s primitive type to a string, we can use the class method valueOf in the String class. The method is overloaded so that its parameter can be of any primitive type. Example 9a) String.valueOf(123) returns "123"b) String.valueOf('a') returns "a" c) String.valueOf(2.5) returns "2.5" Java allows us to chain instance method in order to produce compound effects. This can be very effective in operations involving strings. Given an expression of the form |