The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Searching for a Character or a Substring within a String

The String class provides two accessor methods that return the position within the string of a specific character or substring: indexOf and lastIndexOf. The indexOf method searches forward from the beginning of the string, and lastIndexOf searches backward from the end of the string. The following table describes the various forms of the indexOf and lastIndexOf methods.

The indexOf and lastIndexOf Methods in the String Class
Method Description
int indexOf(int)
int lastIndexOf(int)
Returns the index of the first (last) occurrence of the specified character.
int indexOf(int, int)
int lastIndexOf(int, int)
Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.
int indexOf(String)
int lastIndexOf(String)
Returns the index of the first (last) occurrence of the specified string.
int indexOf(String, int)
int lastIndexOf(String, int)
Returns the index of the first (last) occurrence of the specified string, searching forward (backward) from the specified index.

The StringBuffer and StringBuilder classes does not support the indexOf or the lastIndexOf methods. If you need to use these methods on such an object, first convert the string buffer to a string by using its toString method.

The following class, Filename (in a .java source file), illustrates the use of lastIndexOf and substring to isolate different parts of a file name.


Note: The methods in the following Filename class 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.
// 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);
    }
}
Here's a small program that constructs a Filename object and calls all of its methods:
public class FilenameDemo {
    public static void main(String[] args) {
        final String FPATH = "/home/mem/index.html";
        Filename myHomePage = new Filename(FPATH,
                                           '/', '.');
        System.out.println("Extension = " + 
             myHomePage.extension());
        System.out.println("Filename = " + 
             myHomePage.filename());
        System.out.println("Path = " + 
             myHomePage.path());
    }
}
And here's the output from the program:
Extension = html
Filename = index
Path = /home/mem
As shown in the following figure, our extension method uses lastIndexOf to locate the last occurrence of the period (.) in the file name. Then substring uses the return value of lastIndexOf to extract the file name extension—that is, the substring from the period to the end of the string. This code assumes that the file name has a period in it; if the file name does not have a period, lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException.

The use of lastIndexOf and substring in the extension method

Also, notice that the extension method uses dot + 1 as the argument to substring. If the period character (.) is the last character of the string, dot + 1 is equal to the length of the string, which is one larger than the largest index into the string (because indices start at 0). This is a legal argument to substring because that method accepts an index equal to but not greater than the length of the string and interprets it to mean "the end of the string."


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.