How do I get a part or a substring of a string?

The following code snippet demonstrates how to get some part from a string. To do this we use the String.substring() method. The first substring() method take a single parameter, beginIndex, the index where substring start. This method will return part of string from the begin index to the end of the string.

The second method, substring(int beginIndex, int endIndex), takes the begin index and the end index of the substring operation. The index of this substring() method is a zero-based index, this means that the first character in a string start at index 0.

package org.kodejava.example.lang;

public class SubstringExample {
    public static void main(String[] args) {
        // This program demonstrate how we can take some part of a string 
        // or the what we called as substring. Java String class provides 
        // substring method with some overloaded parameter.
        String sentence = "The quick brown fox jumps over the lazy dog";

        // The first substring method with single parameter beginIndex 
        // will take some part of the string from the beginning index 
        // until the last character in the string.
        String part = sentence.substring(4);
        System.out.println("Part of sentence: " + part);

        // The second substring method take two parameters, beginIndex 
        // and endIndex. This method returns the substring start from 
        // beginIndex to the endIndex.
        part = sentence.substring(16, 30);
        System.out.println("Part of sentence: " + part);
    }
}

This code snippet print out the following result:

Part of sentence: quick brown fox jumps over the lazy dog
Part of sentence: fox jumps over

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply