Sunday, December 12, 2010

Java Substring Examples

Welcome back to Java Code Online. Today we would be discussing examples of Java substring() method. Substring is a method of the String class in Java. It is used to extract a part of the original String. The examples for Java substring() function are shown below.

Get a character from a String using substring()
This example extracts a character from the specified index value using the substring method.

    package JavaTest1;

    //Get a character at a specified index using substring
    public class SubStringChar {

        public static void main(String[] args) {

            String str = "substring() method example";
            String singleStr;

            singleStr = str.substring(5, 6);


When the above code is executed, the output is:-

The above code is useful when we want to extract a single character from a string. There are other methods also in the String class which can perform the above operation like charAt().

Get a substring from a string using the substring() method
The above example could be modified to extract a substring from the original String. The code is show below:-

    package JavaTest1;

    public class SubStringPart {

        public static void main(String[] args) {

            String str = "substring() method example";
            String singleStr;

            singleStr = str.substring(5, 16);


The output of the above code is:-
      ring() meth

A very useful example when we want to extract some part of a string.

Search for a file type using substring() method
Suppose that we want to search a directory for a particular file type. We have many files in the directory, but we want a single file that is of a particular type (for example "pdf"). There are other files also in the directory which are of other file types(for example html, ppt, xml, xls, etc.).

The code below searches the directory for a pdf file and returns the name of the first pdf file found. This name could be used for reading the file in java, or for checking that a particular file type is present or not.

    package JavaTest1;


    public class SearchSubString {

        private static final String fileExtensionDesired = "pdf";

        public static void main(String[] args) {

            String fileName = null;
            String fileExtension = null;
            String fileFound = null;

            int indexVal = 0;

            // Note the "\\" used in the path of the directory instead of "\",
            // this is required to read the path in the String format.

            File f = new File("D:\\JavaCodeFile");

            // Check if the directory exists
            if (f.exists()) {
                 * Retrieve all the files in the directory in the form of a File
                 * Array
                File[] fileArray = f.listFiles();

                for (int i = 0; i < fileArray.length; i++) {

                    // Get the file name and in a String
                    fileName = fileArray[i].getName();

                    // Get the index value of extension of the file
                    indexVal = fileName.lastIndexOf(".");

                    // Extension of the file starts from indexVal + 1
                    fileExtension = fileName.substring(indexVal + 1);

                    if (fileExtension.equals(fileExtensionDesired)) {

                        fileFound = fileName;

                        // Since we have found the first file, we can exit the
                        // for loop
                    } else {
                        fileFound = null;

                // if the file is found
                if (null != fileFound) {
                    // Display the name of the pdf file we were looking
                    System.out.println("Got the desired file: " + fileFound);
                    System.out.println("No file found with the extension: " + fileExtensionDesired);
            } else {
                System.out.println("The directory does not exist");

When the above code is run on my machine, then the output is:-
      Got the desired file: JavaString.pdf

That's all from my side for the day. I hope the substring examples were helpful. Keep buzzing Java Code Online.

Related Readings
Java Substring Index
Search and Replace a Substring in Java Example 
Java Substring Compare Example 
Delete a Substring From a String Using Java

Related Articles

Convert int to String in Java
Convert int to String using Wrapper in Java
Java String Length Program
Reverse a String in Java

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.