|
|
The String and StringBuffer Classes |
For the
StringClassIn addition to thelengthandcharAtaccessors you saw on the previous page, theStringclass provides two accessors that return the position within the string of a specific character or string:indexOfandlastIndexOf. TheindexOfmethod searches forward from the beginning of the string, andlastIndexOfsearches backward from the end of the string.The
indexOfandlastIndexOfmethods are frequently used withsubstring, which returns a substring of the string. The following class illustrates the use oflastIndexOfandsubstringto isolate different parts of a filename.
Note: The methods in the followingFilenameclass don't do any error checking and assume that their argument contains a full directory path and a filename with an extension. If these methods were production code they would verify that their arguments were properly constructed.
Here's a small program that constructs a// This class assumes that the string used to initialize // fullPath has a directory path, filename, and extension. // The methods won't work if it doesn't. public class Filename { private String fullPath; private char pathSeparator, extensionSeparator; public Filename(String str, char sep, char ext) { fullPath = str; pathSeparator = sep; extensionSeparator = ext; } public String extension() { int dot = fullPath.lastIndexOf(extensionSeparator); return fullPath.substring(dot + 1); } public String filename() { int dot = fullPath.lastIndexOf(extensionSeparator); int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(sep + 1, dot); } public String path() { int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(0, sep); } }Filenameobject and calls all of its methods:And here's the output from the program:public class FilenameTest { public static void main(String[] args) { Filename myHomePage = new Filename("/home/mem/index.html", '/', '.'); System.out.println("Extension = " + myHomePage.extension()); System.out.println("Filename = " + myHomePage.filename()); System.out.println("Path = " + myHomePage.path()); } }TheExtension = html Filename = index Path = /home/mem/public_htmlextensionmethod useslastIndexOfto locate the last occurrence of the period (.) in the filename. Thensubstringuses the return value oflastIndexOfto extract the filename extension--that is, the substring from the period to the end of the string. This code assumes that the filename actually has a period in it; if the filename does not have a period , thenlastIndexOfreturns -1, and thesubstringmethod throws aStringIndexOutOfBoundsException.Also, notice that
extensionusesdot + 1as the argument tosubstring. If the period character is the last character of the string, thendot + 1is equal to the length of the string which is one larger than the largest index into the string (because indices start at 0). However,substringaccepts an index equal to but not greater than the length of the string and interprets it to mean "the end of the string."Try this: Inspect the other methods in the
Filenameclass and notice how thelastIndexOfandsubstringmethods work together to isolate different parts of a filename.While the methods in the example above use only one version of the
lastIndexOfmethod, theStringclass actually supports four different versions of both theindexOfandlastIndexOfmethods. The four versions work as follows:
indexOf(int character)lastIndexOf(int character)- Return the index of the first (last) occurrence of the specified character.
indexOf(int character, int from)lastIndexOf(int character, int from)- Return the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.
indexOf(String string)lastIndexOf(String string)- Return the index of the first (last) occurrence of the specified String.
indexOf(String string, int from)lastIndexOf(String string, int from)- Return the index of the first (last) occurrence of the specified String, searching forward (backward) from the specified index.
For the
StringBufferClassLikeString,StringBufferprovideslengthandcharAtaccessor methods. In addition to these two accessors,StringBufferalso has a method calledcapacity. Thecapacitymethod differs fromlengthin that it returns the amount of space currently allocated for theStringBuffer, rather than the amount of space used. For example, the capacity of theStringBufferin thereverseItmethod shown here never changes, while the length of theStringBufferincreases by one for each iteration of the loop:public class ReverseString { public static String reverseIt(String source) { int i, len = source.length(); StringBuffer dest = new StringBuffer(len); for (i = (len - 1); i >= 0; i--) dest.append(source.charAt(i)); return dest.toString(); } }
|
|
The String and StringBuffer Classes |